# How to Sort an Array in JavaScript

Array.sort()

Page content

In this tutorial, we’ll learn how to sort an Array in JavaScript by using `Array.sort()` method.

## Sort String Array

Let’s create a string array:

``````const fruits = ['mango', 'cherry', 'berries', 'apple', 'banana', 'kiwi'];
``````

We can sort the array elements in ascending alphabetical (a-z, A-Z) order using `sort()` method:

``````fruits.sort();
console.log(fruits);
``````
``````▶ (6) ["apple", "banana", "berries", "cherry", "kiwi", "mango"]
``````

We can also sort the array elements in descending alphabetical (z-a, Z-A) order using `reverse()` method:

``````fruits.reverse();
console.log(fruits);
``````
``````▶ (6) ["mango", "kiwi", "cherry", "berries", "banana", "apple"]
``````

## Sort Number Array

The built-in `sort()` and `reverse()` methods sort the array elements in alphabetical order so it is not useful when it comes to number array. Fortunately, `sort()` methods takes compare functions as an argument which can be used to override its default sorting behavior.

Let’s first create our compare function:

###### Compare Function
``````function(a, b) {return a - b}
``````

When the `sort()` method compares two values, it sends the values to our compare function and sorts the values according to the returned value.

• If the result is negative, a is sorted before b.
• If the result is positive, b is sorted before a.
• If the result is 0, nothing changes.

Let’s sort number array in ascending order using `sort()` with compare function:

``````const numbers = [1, 7, 3, 5, 8, 2, 9, 4, 6];

numbers.sort(function(a, b){return a - b});     //ascending
console.log(numbers);
``````
``````▶ (9) [1, 2, 3, 4, 5, 6, 7, 8, 9]
``````

We need to reverse the subtraction from (a - b) to (b - a) in compare function, if we want to sort the numbers in descending order:

``````const numbers = [1, 7, 3, 5, 8, 2, 9, 4, 6];

numbers.sort(function(a, b){return b - a});    //descending
console.log(numbers);
``````
``````▶ (9) [9, 8, 7, 6, 5, 4, 3, 2, 1]
``````