Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
array
sort

JavaScript array.sort() method

Educative Answers Team

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);

RELATED TAGS

javascript
array
sort
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring