使用 JavaScript 获取数组中第三小的数字


问题

我们需要写一个 JavaScript 函数,它接收一个长度至少为 3 的数字数组。

我们的函数应该从数组中返回第三小的数字。

示例

以下是代码 −

 实时演示

const arr = [6, 7, 3, 8, 2, 9, 4, 5];
const thirdSmallest = () => {
   const copy = arr.slice();
   for(let i = 0; i < 2; i++){
      const minIndex = copy.indexOf(Math.min(...copy));
      copy.splice(minIndex, 1);
   };
   return Math.min(...copy);
};
console.log(thirdSmallest(arr));

输出

4

更新于: 2021 年 4 月 17 日

519 次浏览

开启你的职业

通过完成课程并获得认证

开始
广告
© . All rights reserved.