• Post category:JavaScript

Today, we will explain to you how to sorting an array in JavaScript using sort method of the array. Sorting is nothing but lets you arrange data in a required form.

The sort() method is used to rearranges the elements of an array in order and returns that array. The sort order can be alphabetic, numeric, ascending or descending. By default, sort() method is alphabetic order for the words and ascending order for the numbers.

## Different ways to Sort an Array in JavaScript

### 1. Sort method

The sort() method sorts the elements into an alphabetical order and returns the sorted array. This method works well for strings not for number.

``````var colours = ["Blue", "Orange", "White", "Pink"];
colours.sort();

// Output: ["Blue", "Orange", "Pink", "White"]``````

If we use sort() method for numerical array, the results aren’t what we might expect. Because the numeric array gets converted to a string by the sort() method. see below example.

``````var numbers = [84,45,7,0,17,34,28]
numbers.sort();

// Output: [0, 17, 28, 34, 45, 7, 84]``````

So, we have to customize the array sort. To customize the sort order, we pass function to compare two items in the array and sends the values to the compare function. The compare function follows the below test cases:

• If the compare function returns a value less than 0, a is sorted before b.
• If the compare function returns a value greater than 0, b is sorted before a.
• If the compare function returns 0, then no change appears in the sort order of the values a & b.

### 2. Sorting array in ascending order

The below example describes how to sort the array in ascending order.

``````var numbers = [84,45,7,0,17,34,28]
numbers.sort((a, b) => a - b);

// Output: [0, 7, 17, 28, 34, 45, 84]``````

### 3. Sorting array in descending order

Check below example that describes how to sort the array in descending order.

``````var numbers = [84,45,7,0,17,34,28]
numbers.sort((a, b) => b - a);

// Output: [84, 45, 34, 28, 17, 7, 0]``````

### 4. Reversing the sorted array

To reverse the sorted array, first we have to sort an array using sort method that after reverse the sorted array using reverse method.

``````var colours = ["Blue", "Orange", "White", "Pink"]
colours.sort();
colours.reverse();

// Output: ["White", "Pink", "Orange", "Blue"]``````

Thank you for reading! Happy Coding!