从数组中获取第二个最小元素,无需排序 JavaScript

javascriptweb developmentobject oriented programming更新于 2025/10/22 0:12:17

我们有一个数字数组,我们需要编写一个函数来返回数组中的第二小值。

例如 − 如果数组是 −

const arr = [67, 87, 56, 8, 56, 78, 54, 67, 98, 56, 54];

然后输出应该是以下 −

54

因为 54 是 8 之后最小的值

示例

const arr = [67, 87, 56, 8, 56, 78, 54, 67, 98, 56, 54];
const minimumIndex = arr => {
   return arr.indexOf(Math.min(...arr));
};
const secondMinimum = arr => {
   const copy = arr.slice();
   copy.splice(minimumIndex(copy), 1);
   return copy[minimumIndex(copy)];
};
console.log(secondMinimum(arr));

输出

控制台中的输出将是 −

54

相关文章


有用资源