Hey I've been trying to return the 2 smallest numbers from an array, regardless of the index. Can you please help me out?
Asked
Active
Viewed 7,634 times
2
-
1Did you mean `array`? – kind user Apr 06 '17 at 14:35
-
Hello, yep, sorry – Ivayloi Apr 06 '17 at 14:37
2 Answers
4
- 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);

kind user
- 40,029
- 7
- 67
- 77
-
1
-
NOTE: This mutates the array. You need a copy if you do not want to change the array. Also no need for `res = arr` since arr is sorted in place – mplungjan Oct 23 '18 at 12:46
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());

Jaromanda X
- 53,868
- 5
- 73
- 87