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
.
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.
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.
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.
function findLongestWord(str) { var longestWord = str. split(' '). reduce(function(longest, currentWord) { return currentWord. length > longest.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With