In this tutorial, you will learn how to use the JavaScript Array sort() method to sort arrays of numbers, string, and objects.

Introduction to JavaScript Array sort() method

The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array.

By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.

The sort() method casts elements to strings and compares the strings to determine the orders.

Consider the following example:

let numbers = [0, 1 , 2, 3, 10, 20, 30 ];
numbers.sort();
console.log(numbers);

The output is:

[ 0, 1, 10, 2, 20, 3, 30 ]

In this example, the sort() method places 10 before 2 because the string “10” comes before “2” when doing a string comparison.

To fix this, you need to pass a compare function to the sort() method. The sort() method will use the compare function to determine the orders of elements.

The following illustrates the syntax of the sort() method:

array.sort(comparefunction)

The sort() method accepts an optional argument which is a function that compares two elements of the array.

If you omit the compare function, the sort() method sorts the elements with the sort order based on the Unicode code point values of elements as mentioned earlier.

The compare function of the sort() method accepts two arguments and returns a value that determines the sort order. The following illustrates the syntax of the compare function:

function compare(a,b) {
  // ...
}

The compare() function accepts two arguments a and b. The sort() method will sort elements based on the return value of the compare() function with the following rules:

  1. If compare(a,b) is less than zero, the sort() method sorts a to a lower index than b. In other words, a will come first.
  2. If compare(a,b) is greater than zero, the sort() method sort b to a lower index than a, i.e., b will come first.
  3. If compare(a,b) returns zero, the sort() method considers a equals b and leaves their positions unchanged.

To fix the issue of sorting the number, you can use the following syntax:

let numbers = [0, 1 , 2, 3, 10, 20, 30 ];
numbers.sort( function( a , b){
    if(a > b) return 1;
    if(a < b) return -1;
    return 0;
});

console.log(numbers);

Output:

[ 0,  1,  2, 3, 10, 20, 30 ]

Or you can define the comparison function using the arrow function syntax:

let numbers = [0, 1 , 2, 3, 10, 20, 30 ];
numbers.sort((a,b) => {
    if(a > b) return 1;
    if(a < b) return -1;
    return 0;
});

console.log(numbers);

And the following is the simplest since the elements of the array are numbers:

let numbers = [0, 1, 2, 3, 10, 20, 30];
numbers.sort((a, b) => a - b);

console.log(numbers);

#javascript #programming #developer #web-development

JavaScript Array sort: Sorting an Array More Effectively
1.85 GEEK