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



嘿,我一直在尝试从数组中返回 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());

最新更新