在 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' ]