获取数组JavaScript中最长和最短的字符串
我们有这样的字符串文字数组-
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a', 'sentence.'];
我们需要编写一个函数,该函数返回该数组中最长和最短的单词。我们将使用Array.prototype.reduce()方法通过完整的迭代来跟踪数组中最长和最短的单词。
为此的代码将是-
示例
const arr = ['Some', 'random', 'words', 'that', 'actually', 'form', 'a',
'sentence.'];
const findWords = (arr) => {
return arr.reduce((acc, val) => {
const { length: len } = val;
if(len > acc['longest']['length']){
acc['longest'] = val;
}else if(len < acc['shortest']['length']){
acc['shortest'] = val;
};
return acc;
}, {
longest: arr[0],
shortest: arr[0]
});
};
console.log(findWords(arr));输出结果
控制台中的输出将为-
{ longest: 'sentence.', shortest: 'a' }