JavaScript Array Sorting

sort() The method is one of the most powerful array methods.

Array sorting

sort() The method sorts the array in alphabetical order:

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();            // Sort the elements in fruits

Try It Yourself

Reverse the array

reverse() This method reverses the elements in the array.

You can use it to sort the array in descending order:

Example

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();            // Sort the elements in fruits
fruits.reverse();         // Reverse the order of elements

Try It Yourself

Number sorting

By default,sort() The function sorts according toStringto sort the values in order.

This function is suitable for strings ("Apple" will be before "Banana").

However, if numbers are sorted as strings, "25" is greater than "100" because "2" is greater than "1".

For this reason,sort() Method may produce incorrect results when sorting numbers.

We use aComparison functionTo fix this issue:

Example

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b}); 

Try It Yourself

Use the same technique to sort the array in descending order:

Example

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a}); 

Try It Yourself

Comparison function

The purpose of the comparison function is to define a different sorting order.

The comparison function should return a negative, zero, or positive value, depending on the parameters:

function(a, b){return a-b}

When sort() When the function compares two values, it sends the values to the comparison function and sorts these values based on the returned value (negative, zero, or positive).

Example:

When comparing 40 and 100,sort() The method calls the comparison function function(40,100).

The function calculates 40-100, then returns -60 (a negative value).

The sorting function will sort 40 as a lower value than 100.

You can use the following code snippet to test numeric and alphabetical sorting:

<button onclick="myFunction1()">Sort by Alphabetical Order</button>
<button onclick="myFunction2()">Sort by Number Order</button>
<p id="demo"></p>
<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction1() {
		points.sort();
		document.getElementById("demo").innerHTML  = points;
}
function myFunction2() {
		points.sort(function(a, b){return  a - b});
		document.getElementById("demo").innerHTML = points;
}
</script>

Try It Yourself

Sort the array in random order

Example

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return 0.5 - Math.random()}); 

Try It Yourself

Finding the highest (or lowest) array value

JavaScript does not provide a built-in function to find the maximum or minimum value in an array.

However, after sorting the array, you can use the index to obtain the highest or lowest value.

Ascending order sorting:

Example

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a - b});
// Now points[0] contains the lowest value
// And points[points.length-1] contains the highest value

Try It Yourself

Descending order sorting:

Example

var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b - a});
// Now points[0] contains the highest value
// And points[points.length-1] contains the lowest value

Try It Yourself

If you only need to find the highest or lowest value, sorting the entire array is a very inefficient method.

to use Math.max() on an array

You can use Math.max.apply to find the highest value in the array:

Example

function myArrayMax(arr) {
    return Math.max.apply(null, arr);
}

Try It Yourself

Math.max.apply([1, 2, 3]) equals Math.max(1, 2, 3).

to use Math.min() on an array

You can use Math.min.apply to find the lowest value in the array:

Example

function myArrayMin(arr) {
    return Math.min.apply(null, arr);
}

Try It Yourself

Math.min.apply([1, 2, 3]) equals Math.min(1, 2, 3).

My Min/Max JavaScript Method

The fastest solution is to use a "homebrew" method.

This function traverses the array and compares each value with the highest value found:

Example (find Max)

function myArrayMax(arr) {
    var len = arr.length
    var max = -Infinity;
    while (len--) {
        if (arr[len] > max) {
            max = arr[len];
        }
    }
    return max;
}

Try It Yourself

This function traverses the array and compares each value with the lowest value found:

Example (find Min)

function myArrayMin(arr) {
    var len = arr.length
    var min = Infinity;
    while (len--) {
        if (arr[len] < min) {
            min = arr[len];
        }
    }
    return min;
}

Try It Yourself

Sorting Object Arrays

JavaScript arrays often contain objects:

Example

var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}];

Even if objects have properties of different data types,sort() This method can still be used to sort arrays.

The solution is to compare attribute values using a comparison function:

Example

cars.sort(function(a, b){return a.year - b.year});

Try It Yourself

Comparing string properties can be slightly more complex:

Example

cars.sort(function(a, b){
	  var x = a.type.toLowerCase();
	  var y = b.type.toLowerCase();
	  if (x < y) {return -1;}
	  if (x > y) {return 1;}
	  return 0;
});

Try It Yourself