Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 574
Luis Daniel Arciniegas Barco Avatar asked Jan 21 '26 10:01

Luis Daniel Arciniegas Barco


1 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))
like image 59
Anders Grandjean-Thomsen Avatar answered Jan 23 '26 04:01

Anders Grandjean-Thomsen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!