js中如何获取数组中最小的两个数?

How can I get the smallest two numbers from an array in js?

嘿,我一直在尝试 return 数组中的 2 个最小数字,而不考虑索引。你能帮帮我吗?

  • 按升序排列数组。
  • 使用Array#slice获取前两个元素(最小的)。

var arr = [5, 4, 7, 2, 10, 1],
    res = arr.sort((a,b) => a - b).slice(0, 2);
    console.log(res);

虽然接受的答案很好而且正确,但原始数组已排序,这可能不是我们想要的

var arr = [5, 4, 7, 2, 10, 1],
    res = arr.sort((a,b) => a - b).slice(0, 2);
console.log(arr.join()); // note it has mutated to 1,2,4,5,7,10
console.log(res.join());

您可以通过 slice 原始数组并在这个新副本上排序来避免这种情况

我还添加了按降序排列的最低两个值的代码,因为这也可能有用

const array = [1, 10, 2, 7, 5,3, 4];
const ascending = array.slice().sort((a, b) => a - b).slice(0, 2);
const descending = array.slice().sort((a, b) => b - a).slice(-2);

console.log(array.join()); // to show it isn't changed
console.log(ascending.join());
console.log(descending.join());