Follow The New Tutorial updates on WhatsApp, Telegram or YouTube.

JavaScript Array sort() method

JavaScript Array sort() method is used to arrange the array elements in some order.

In this tutorial, you will learn about the JavaScript Array sort() method with the help of examples.

By default, sort() method follows the ascending order.

The sort() overwrites the original array.

The sort() sorts the elements as strings in alphabetical and ascending order.

sort() is an ECMAScript1 (ES1) feature.

The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.

Syntax

array.sort(compareFunction)

Parameters

compareFunction – It is optional. It represents a function that provides an alternative sort order. It is used to define a custom sort order. The function should return a negative, zero, or positive value, depending on the arguments.

  • function(a, b){return a-b}

When sort() compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.

  • If returned value < 0a is sorted before b (a comes before b).
  • If returned value > 0b is sorted before a (b comes before a).
  • If returned value == 0a and b remain unchanged relative to each other.
  • The sort function will sort 40 as a value lower than 100.
  • When comparing 40 and 100, sort() calls the function(40,100).
  • The function calculates 40-100, and returns -60 (a negative value).

Return Value

An array of sorted elements.

Examples

const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]

const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]

Sort numbers in ascending order:

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});

Sort numbers in descending order:

const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});