JavaScript array.sort() method

An array.sort() function is used to sort an array in JavaScript. By default, it sorts the array in ascending order.

Syntax

array.sort() is called on the array we want to sort. However, by default, it considers the elements of the array as strings; “100” is lower than “50” because “1” comes before “5”.

To avoid this, an optional argument, which is a user-defined compare function, can be passed to this function.


compareFunction(a, b)

In case we pass this optional parameter, the sort() method takes the value at index 0 as a and every other value one by one as b to pass on to this compare function. Sorting is then done based on its return value:

  1. return value < 0 : a is placed before b.
  2. return value > 0 : a is placed after b.
  3. return value = 0 : Keeps the same order as in the original array.

How the compare function works:

1 of 4

Example

The example below shows a numeric array sorted with and without a compare function:

var numbers = [50, 100, 2, 0];
// Without compare function
console.log("Without compare function:");
numbers.sort();
console.log(numbers);
// With a compare function
console.log("With a compare function:");
numbers.sort(function(a, b){
return a - b;
});
console.log(numbers);

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved