How to sort numbers? [duplicate]

The JavaScript sort() function may or may not take a parameter.
The parameter would be a function – meaning what function is to be used to assess which of two elements should be before the other.

The n array is made of strings representing numbers.
Doing a simple sort() without a function, an alphabetical order would be used: the result would be

 "1", "10", "25"... "5"

and is not correct.

Providing a function, sortNumber, tells sort to call that function with two elements of the array each time the sort algorithm wants to know which of the two items is before the other.

Thus sortNumber provided with two items, does a numerical operation to return either

  • a negative value, meaning a is before b
  • a positive value, b is before a
  • zero: they’re equal in terms of order (order doesn’t matter).

Leave a Comment