Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return longest string in array (JavaScript) [duplicate]

So I'm trying to find the longest string in an array of strings. I've done a problem similar to this before where I had to return the length of the longest string. The thing is, my code works and returns 11 when it looks like this:

var long1= 0;

var plorp = ["bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"];

function longestString(arr){
  for (i=0; i<arr.length; i++){
      if (arr[i].length > long1){
        long1= arr[i].length;
      }

  }
  return long1;
}

but, if I change long1= arr[i].length; to long1 = arr[i]; it just returns arr[0] instead. Am I missing something here? The loop seems to be iterating correctly otherwise.

Edit: that is to say, it returns bbllkw.

like image 599
leandraaar Avatar asked Sep 08 '17 23:09

leandraaar


People also ask

How do you find the maximum length of a string in an array?

Approach: Follow the steps below to solve the problem: Traverse the given array of strings. Calculate the maximum length among all the strings from the array and store it in a variable, say len. Now, traverse the array of string again and print those strings from the array having a length equal to len.

How do you find the longest word in an array?

The For loop method Split the word into an array immediately using split(). After doing this, initialize the longest word to an empty string. Then use the for loop to map over the items in the array. The longest word returns as the word with the longest index.

How do you duplicate an array in JavaScript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.

How do you find the longest word in JavaScript?

function findLongestWord(str) { var longestWord = str. split(' '). reduce(function(longest, currentWord) { return currentWord. length > longest.


1 Answers

You can use reduce instead:

var plorp = ["bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"];
var longest = plorp.reduce(function(a, b) { 
  return a.length > b.length ? a : b
}, '');
console.log(longest);

Or ES6 version:

var plorp = ["bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"];
var longest = plorp.reduce((a, b) => a.length > b.length ? a : b, '');
console.log(longest);
like image 58
Dekel Avatar answered Oct 07 '22 03:10

Dekel