Updated after the user was offered a more basic solution.
Here we find the longest length of an array element using the reduce function, and then filter the array with elements that have this length using the filter function. It returns us several elements if they have the same but the longest length.
var plorp = ['sameLength', 'someoth', 'asfzc', 'sameLLngth']; ln = plorp.reduce((r,s) => r > s.length ? r : s.length, 0); const result = plorp.filter(pl => pl.length == ln); console.log(result);
Old answer
If there is more than one longest string in the array, it will return an array of them. If there is only one long, it will return a string, not an array.
var plorp = ["bbllkw", "oox", "ejjuyyy", "plmiis", "xxxzgpsssa", "xxwwkktt", "znnnnfqknaz", "qqquuhii", "dvvvwz"]; var wholeArr = []; function longestString(arr) { var tlength = 0; for(var i =0; i < plorp.length; i++){ if(tlength < plorp[i].length){ tlength = plorp[i].length; } } for(var j =0; j < plorp.length; j++){ if(plorp[j].length == tlength){ wholeArr.push(plorp[j]); } } if(wholeArr.length == 1){ return wholeArr[0] }else{ return wholeArr } } console.log(longestString(plorp));
source share