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

限于喜欢 提交于 2019-12-17 21:19:56

问题


Hey I've been trying to return the 2 smallest numbers from an array, regardless of the index. Can you please help me out?


回答1:


  • Sort the array in the ascending order.
  • Use Array#slice to get the first two elements (the smallest ones).

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



回答2:


While the accepted answer is good and correct, the original array is sorted, which may not be desired

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());

You can avoid this by sliceing the original array and sorting on this new copy

I also added code for the lowest two values in descending order, as that may also be useful

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());


来源:https://stackoverflow.com/questions/43258279/how-can-i-get-the-smallest-two-numbers-from-an-array-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!