问题
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 slice
ing 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