Can anyone tell me how this code sorts array ascendingly...this one blown me :*

function ascendingOrder(arr) {
  return arr.sort(function(a, b) {
    return a - b;
  });
}
ascendingOrder([1, 5, 2, 3, 4]);

Because the sort function sorts the array based on the return value. If a - b returns a negative value, a is put before b in the array, so the lower number always gets put before bigger numbers, hence it’s sorted in an ascending way.

2 Likes

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.