从 JavaScript 字符串数组中查找最小元素


我们需要编写一个 JavaScript 函数来接收一个字符串数组,并返回长度最短的字符串的索引。

我们将简单地使用一个 for 循环,并保存长度最短的字符串的索引。

因此,让我们编写此函数的代码 −

实例

其代码如下 −

const arr = ['this', 'can', 'be', 'some', 'random', 'sentence'];
const findSmallest = arr => {
   const creds = arr.reduce((acc, val, index) => {
      let { ind, len } = acc;
      if(val.length < len){
         len = val.length;
         ind = index;
      };
      return { ind, len };
   }, {
      ind: -1,
      len: Infinity
   });
   return arr[creds['ind']];
};
console.log(findSmallest(arr));

输出

控制台中的输出如下 −

be

更新日期:2020 年 10 月 22 日

230 次浏览

职业生涯起航

完成课程获得认证

开始
广告
© . All rights reserved.