How to find the longest word in a String within an Array in JS

Viewed 287

It could be some embarassing, but I'm really new into JS and prior to be accepted in a BootCamp they asked me this excersice the which consist in finding the longest word in a string within the array.

i.e ['The Soviet Union', 'The Consomol', 'United States'] should return Consomol.

I have tried hours and hours of surfing and I only saw how to get the longest word or the longest string, but my interest is how to get the longest word within a given phrase within an array. I wrote this code the which...

function longest_string(str_ara) {
var max = str_ara[0].length;
  str_ara.map(v => max = Math.max(max, v.length));
  result = str_ara.filter(v => v.length == max);
  return result;
}

Code above gives me the longest string, not the longest word of the array. I would like a way to add to find the longest word either with other. Thanks

3 Answers

Hope I understood the question correctly - otherwise let me know..

If you'll need further explanation let me know aswell

const items = ['The Soviet Union', 'The Consomol', 'United States'];

let longestWord = '';

// Loop through every item in the array
items.forEach((item) => {

  // Let's split it by space ex. 'The Soviet Union' === ['The', 'Soviet', 'Union']
  const words = item.split(" ");
  
  // Loop through each word in the new array
  words.forEach((word) => {
    // Check if current word is longer than the one we already saved
    if (word.length > longestWord.length) {
      // If longer - let's update
      longestWord = word
    }
  });
});

// All done - let's output the longest word
console.log(longestWord)

Edited:

To use it as a function you could do something like this:

const wordArray = ['The Soviet Union', 'The Consomol', 'United States'];

function extractLongestWord(items) {
  let longestWord = '';
  items.forEach((item) => {
    const words = item.split(" ");
    words.forEach((word) => {
      if (word.length > longestWord.length) {
        longestWord = word
      }
    });
  });
  
  return longestWord;
 }
 
 console.log(extractLongestWord(wordArray))

you can use array function like split, flat, reduce, map.

here is a solution:

const inputs = ['The Soviet Union', 'The Consomol', 'United States'];
const words = inputs.map(input => input.split(' ')).flat();
const maxLength = words.reduce((acc, cur) => acc.length > cur.length ? acc : cur, '');

console.log(maxLength);
const longest_string = stringArray => {
    let longestWord = "";
    stringArray.forEach(string => {
        string.split(" ").forEach(word => {
            longestWord = (word.length > longestWord.length) ? word : longestWord 
        })
    })
    return longestWord
}

const test_input = ['The Soviet Union', 'The Consomol', 'United States']
console.log(longest_string(test_input))
// outputs "Consomol"
Related