Updated June 19, 2023

## Introduction to JavaScript Array Sort

Sorting means arranging items in a specific order. Array Sorting means arranging the elements in either ascending or descending order. Array sorting can be performed with strings and numbers.

**Real-time Example**: When we want to sort out Amazon products based on price, brand company, product name, etc. It is difficult to iterate the items with for loop or a while loop because the execution time is more. So, instead of that, we can use predefined methods provided by JavaScript. That is sort(), reverse(), etc.

### How does Array Sort work in JavaScript?

- Sorting the strings sort() predefined function is preferable.

**Syntax:**

`Array["string1","string2","string3"].sort(); //ascending order by default`

- By default, the sort() function sorting is in ascending order.
- If we want descending order, apply a reverse() function on the sort() function result.

**Syntax:**

```
var ascend=Array["string1","string2","string3"].sort();
ascend.reverse(); //descending order
```

- When sorting the numbers sort() function is not recommended because it works accurately with strings.
- The sorting numbers compare function is recommendable for accurate results.

**Syntax:**

`Array[number1, number2,number3].sort(function(x,y){ return x-y}); // ascending order`

- Above sorting is in ascending order; if we want descending order by changing return a-b as return b-a.

**Syntax:**

`Array[number1, number2,number3].sort(function(x,y){ return y-x}); // descending order`

- Sort(function(x,y)) every time takes 2 values compares

**Note:**function(1

^{st},2

^{nd}), function(2

^{nd},3

^{rd}), function(3

^{rd}

^{t},4

^{th}), function(4

^{th},5

^{th})…..until array emptied.

- If return x-y gives negative means, y is greater than x, so x comes before y.
- If return x-y gives positive means, x is greater than y, so y comes before x.
- If return x-y gives 0 means x and y are equal, so values are not swapped.
- This process is similar for return y-x, descending order as well.
- This process repeats until the array is empty.

### Examples of JavaScript Array Sort

Given below are the examples mentioned :

#### Example #1 – Sorting Strings in ascending order

**Code:**

```
<!DOCTYPE html>
<html>
<body>
<font color="green">
<h1 align="center">Sorting Strings Ascending Order</h1>
</font>
<script>
function getStringAscendOrder() {
var alphabets=["Q","z","q","a","m","M","I","i","c","U","u","Z","d","A","C","D"];
var alphabetsSort=alphabets.sort();
document.write(alphabetsSort);
}
getStringAscendOrder();
</script>
</body>
</html>
```

**Output:**

**Explanation:**

- In the above code, we have seen the sorting of the array is in ascending order. But in JavaScript, Uppercase letters are first preceded by lowercase letters.
- So, in the output, All Uppercase letters come first and lowercase letters next in ascending order by applying the sort() function on an array.

#### Example #2 – Sorting Strings in descending order

**Code:**

```
<!DOCTYPE html>
<html>
<body>
<font color="green">
<h1 align="center">Sorting Strings Descending Order</h1>
</font>
<script>
function getStringDescendOrder() {
var alphabets=["Q","z","q","a","m","M","I","i","c","U","u","Z","d","A","C","D"];
var alphabetsSort=alphabets.sort();
document.write(alphabetsSort.reverse());
}
getStringDescendOrder();
</script>
</body>
</html>
```

**Output:**

**Explanation:**

- Get descending elements from an array and apply the sort() function on the array.
- On the resultant array, apply the reverse() function to get exactly the opposite output against ascending order.

Why sort() function not preferable over numbers?

#### Example #3 – Numbers with direct sort() function

**Code:**

```
<!DOCTYPE html>
<html>
<body>
<font color="green">
<h1 align="center"> Sort() function numbers</h1>
</font>
<script>
function getNumbersSort() {
var numbers=[1,-5,0,10,20,9];
document.write(numbers.sort());
}
getNumbersSort ();
</script>
</body>
</html>
```

**Output:**

**Explanation:**

- In the above output, you can see 9 is not greater than 20, even arranged after 20.
- It clearly proved the direct sort() function is not recommendable on numbers.

#### Example #4 – Sorting numbers in ascending order

**Code:**

```
<!DOCTYPE html>
<html>
<body>
<font color="green">
<h1 align="center">Sorting Numbers Ascending Order</h1>
</font>
<script>
function getNumberAscendOrder () {
var numbers=[121,52,47,69,78,-21,0,-52,55,78,-5];
var numbersSort=numbers.sort(function(x,y)
{
return x-y
});
document.write(numbersSort);
}
getNumberAscendOrder();
</script>
</body>
</html>
```

**Output:**

**Explanation:**

- In the above code, the numbers array you passed to compare function inside the sort() function.
- At a time, the function takes just 2 values and compares them.
- Here returns, the resultant is x-y.
- If the result is negative, y comes before x.
- If the result is positive, x comes before y.
- If the result is 0, values are not swapped because values are the same.
- This pattern repeats until the array becomes empty.
- 121-52= positive
- 52,121
- 52,121,47
- 121-47=positive
- 52,47,121
- 52,47,121
- 52-47=positive
- 47,52,121
- 47,52,121,69
- 121-69=positive
- 47,52,69,121

#### Example #5 – Sorting numbers in descending order

**Code:**

```
<!DOCTYPE html>
<html>
<body>
<font color="green">
<h1 align="center">Sorting Numbers Descending Order</h1>
</font>
<script>
function getNumberDescendOrder() {
var numbers=[121,52,47,69,78,-21,0,-52,55,78,-5];
var numbersSort=numbers.sort(function(x,y)
{
return y-x
});
document.write(numbersSort);
}
getNumberDescendOrder ();
</script>
</body>
</html>
```

**Output:**

**Explanation:**

- In the above code, the numbers array you passed to compare function inside the sort() function.
- At a time, the function takes just 2 values and compares them.
- Here returns, the resultant is y-x.
- If the result is negative, x comes before y.
- If the result is positive, y comes before x.
- If the result is 0, values are not swapped because values are the same.
- This pattern repeats until the array becomes empty.
- The output is exactly the opposite of ascending output.

If we want to get the maximum value or minimum value from an array. No need to sort the entire array; we can get it by predefined functions Math.max() and Math.min().

**Syntax:**

```
Math.max(…array);
Math.min(…array);
```

**Note:**Must include 3 dots(…) before an array in the max or min function.

#### Example #6 – Array Maximum and Minimum value

**Code:**

```
<!DOCTYPE html>
<html>
<body>
<font color="green">
<h1 align="center">Maximum and Minimum values from an array </h1>
</font>
<script>
function getMaxAndMinValue() {
var numbers=[121,52,47,69,78,-21,0,-52,55,78,-5];
document.write("Maximum value from "+numbers+" array is =>"+Math.max(...numbers)+"<br>");
document.write("Minimum value from "+numbers+" array is =>"+Math.min(...numbers));
}
getMaxAndMinValue();
</script>
</body>
</html>
```

**Output:**

**Explanation:**

- Just apply the max() function to a given array to get the maximum value from an array.
- Just apply the min() function to a given array to get the minimum value from an array.
- After applying these 2 functions to the array result, the maximum is 121, and the minimum is -52.

### Conclusion

Sorting the string array used the sort function directly, whereas sorting numbers used compare function with the sort function. Uppercase letters are first preferable in a string array. Sorting numbers based on the returned value of negative, positive, and zero resultant.

### Recommended Articles

This is a guide to JavaScript Array Sort. Here we discuss the introduction, how does array sort works in JavaScript? and examples. You may also have a look at the following articles to learn more –