获取数组中最长和最短的字符串 JavaScript

javascriptweb developmentobject oriented programming更新于 2025/10/2 18:20:17

我们有一个像这样的字符串文字数组 −

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' }

相关文章


有用资源