gpt4 book ai didi

javascript - 如何从数组中找到更长的字符串?

转载 作者:行者123 更新时间:2023-12-02 18:08:38 25 4
gpt4 key购买 nike

我想从此数组中找到更长的字符串:

const myArr = ["第一", "第二", "第三", "第四", "第五", "第六", "七", "第八"]

在此数组中,“第二”、“第四”、“第八”的长度为 6。我想以数组形式返回它们。

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)

预期输出:[“第二”,“第四”,“第八”]

但返回 =["first","second"]

最佳答案

如果您使用过滤器,会更容易:

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)

返回:

["second","fourth","eighth"]

或者,正如 Sash 下面提到的,它可以一次性完成,尽管解决方案不那么可读:

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);

关于javascript - 如何从数组中找到更长的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72809389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com