## Introduction to JavaScript Array Sort

Sorting means arrange items in a specific order. Array Sorting means to arrange 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 either by based on price or brand company or product name etc. It is very difficult to iterate the items with for loop or while loop because 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 sort() function sorting is in ascending order.
- If we want descending order, apply reverse() function on 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.
- 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

^{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 not swapped.
- This process similar for return y-x, descending order as well.
- This process repeats until array emptied.

### 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 clearly seen the sorting of the array is in ascending order. But in JavaScript Uppercase letters are first preceded by lower case letters.
- So, in the output, All Uppercase letters come first and lower-case letters next in the ascending order by applying 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 first apply sort() function on array.
- On resultant array apply reverse() function then we will get exactly opposite output against ascending order.

#### Example #3

Why sort() function not preferable over numbers?

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 clearly 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 numbers array passed to compare function inside sort() function.
- At a time, the function takes just 2 values and compares.
- Here returns 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 not swapped because values are the same.
- This pattern repeats until array becomes emptied.
- 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 numbers array passed to compare function inside sort() function.
- At a time, the function takes just 2 values and compares.
- Here returns 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 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 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);
```

#### 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:**

- To get maximum value from an array just apply max() function to a given array.
- To get the minimum value from an array just apply min() function to a given array.
- After applying these 2 functions on the array result for 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 –