在 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 农民朋友发财祝福语简短