It’s Festive Season! Enjoy 30% Off

Use code FESTIVE30 at checkout

Code has been added to clipboard!

array.sort

Reading time 2 min
Published Sep 8, 2017
Updated Oct 10, 2019

JavaScript Array Sort: Main Tips

  • The JavaScript array sort() is used to sort array items.
  • The order in which items are sorted may be either alphabetic or ascending and descending or ascending.
  • This method will change the original array.

sort() Method Explained

The array sort JavaScript function is used to sort array items. It can perform this task in the following orders: numeric or alphabetical, descending or ascending. The method also has a pre-set order, in which case the items are to be sorted in ascending alphabetical order.

To sort text strings with JavaScript sort alphabetically feature, the sort() JavaScript function works sufficiently (Alex goes before Ben). The example below shows how different automobile brands are sorted alphabetically using JavaScript array sort:

Example
var sampleArray = ['Mercedes-Benz', 'Nissan', 'Audi', 'BMW']
var cars = sampleArray.sort();

However, sorting numbers as strings can be problematic. For example, 32 is seen as bigger than 123, since the first character in this number string (3) is bigger than 1.

For this reason, sort() JavaScript method will show incorrect results when dealing with numbers that have more than one digit. You can fix this issue by adding a compare function.

Learn Correct Syntax

To use the array sort JavaScript function properly, you should remember the correct capitalization and its parameters. The first point does not take a lot of effort, and the second one requires a bit of practice.

Take a look at the way this method usually looks (with the compareFunction included):

Array.sort(compareFunction)

Entering the compareFunction is optional. It is used to provide an alternative way to sort the array. This function is supposed to return zero, a negative, or positive value, which depends on the arguments (for example: function(a, b){return a-b}).

Upon comparing the two values, JavaScript array sort will send the values to the compare function, and sort the values based on the returned value. For instance, when 52 and 102 are compared, sort() JavaScript method will call the compare function(52, 102). The function will calculate 52-102, and return -50 (a negative numeric value). Thus, sort() now sorts 52 as a number lower than 102.

Return Value

The return value of the JavaScript array sort function is the sorted array. Of course, the outcome will differ according to the selected sorting order. To sort strings, coders usually make JavaScript sort alphabetically.

Return Value: The original array object with its items sorted according to the given parameters.
JavaScript Version: ECMAScript 1