在 JavaScript 中从数组中查找所有最长的字符串
假设,我们有一个这样的字符串数组-
const arr = [ 'iLoveProgramming', 'thisisalsoastrig', 'Javascriptisfun', 'helloworld', 'canIBeTheLongest', 'Laststring' ];
我们需要编写一个JavaScript函数来接收一个这样的字符串数组。我们函数的目的是挑选所有最长的字符串(如果有多个)。
该函数最终应返回数组中所有最长字符串的数组。
示例
以下是代码-
const arr = [
'iLoveProgramming',
'thisisalsoastrig',
'Javascriptisfun',
'helloworld',
'canIBeTheLongest',
'Laststring'
];
const getLongestStrings = (arr = []) => {
return arr.reduce((acc, val, ind) => {
if (!ind || acc[0].length < val.length) {
return [val];
}
if (acc[0].length === val.length) {
acc.push(val);
}
return acc;
}, []);
};
console.log(getLongestStrings(arr));输出结果以下是控制台上的输出-
[ 'iLoveProgramming', 'thisisalsoastrig', 'canIBeTheLongest' ]
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短