在 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 生日广州男生祝福语简短