1

Specifically I'm looking to sort an array

    array = [1,2,3,4,5,-1,-2,-3,-4,-5];

into

    array = [-5,-4,-3,-2,-1,1,2,3,4,5];
Sage.VS
  • 59
  • 1
  • 6

1 Answers1

2

Try Array.prototype.sort():

array.sort(function(a, b){return a-b});

N.B. This method work only if the values are of type Number. If they are strings, the comparison function will break. It will also fail if the array contains NaN or Infinity.

N.N.B This method mutates the array, i.e. it modifies the array you reference it on, which may or may not be important to you.

Pineda
  • 7,435
  • 3
  • 30
  • 45