I want to find Longer Strings from this array:
const myArr = [“first”, “second”, “third”, “fourth”, “fifth”, “sixth”, “seven”, “eighth”]
in this array “second”,”fourth”,”eighth” has length of 6. I want to return these in an array.
const myArr = ["first", "second", "third", "fourth", "fifth", "sixth", "seven", "eighth"] function longerStrings(arr) { let largeStrings = [] let longerWord = '' for (let name of arr) { if (name.length > longerWord.length) { longerWord = name largeStrings.push(longerWord) } } return largeStrings } longerStrings(myArr)
expected output is: [“second”,”fourth”,”eighth”]
but returns =[“first”,”second”]
Advertisement
Answer
Easier if you use filter instead:
const myArr = ["first", "second", "third", "fourth", "fifth", "sixth", "seven", "eighth"] const longest = myArr.reduce((a, b) => a.length > b.length ? a : b); const res = myArr.filter(el => el.length >= longest.length) console.log(res)
That returns:
["second","fourth","eighth"]
Or, as Sash mentions below, it can be done in a single pass, although the solution is not as readable:
let max = 0; const reducer = myArray.reduce((previous, current) => { if (current.length > max) { previous = []; } if (current.length >= max) { previous.push(current); max = current.length; } return previous; }, []); console.log(reducer);