2

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

John Vandivier
  • 2,158
  • 1
  • 17
  • 23
Ivayloi
  • 49
  • 1
  • 6

2 Answers2

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
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());
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87