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"]
CodePudding user response:
When a word longer than any found so far is identified, you need to create an entirely new array (discarding any elements it had before in it), and put the new record-setting word in it. You also need to push a name to the array if the name being iterated over isn't record-setting, but is equal to the current record-setter.
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 = [name];
} else if (name.length === longerWord.length) {
largeStrings.push(name)
}
}
return largeStrings
}
console.log(longerStrings(myArr));
CodePudding user response:
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);
CodePudding user response:
You could just sort the array by length descending and then select only values which have the same length as the first element:
const myArr = ["first", "second", "third", "fourth", "fifth", "sixth", "seven", "eighth"]
const result = myArr
.sort((a, b) => b.length - a.length)
.filter((v, _, arr) => v.length == arr[0].length)
console.log(result)