0

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
  • 1,830
  • 1
  • 13
  • 21
Ivayloi
  • 29
  • 1
  • 5

2 Answers2

3
  • 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
  • 34,867
  • 6
  • 60
  • 74
1

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
  • 1
  • 4
  • 64
  • 78