Code has been added to clipboard!

JavaScript Sort Array Methods: a Quick & Easy Guide to Array Sort

Reading time 4 min
Published Sep 8, 2017
Updated Oct 2, 2019

As JavaScript arrays can store many objects inside, it can be challenging to sort them out. This tutorial will introduce you to JavaScript sort array methods.

You'll learn plenty of ways how you can sort a JavaScript array. You will also be able to check out numerous examples, which will help you understand the content better.

JavaScript Sort Array: Main Tips

  • One of the most powerful array methods is sort().
  • JS array sorting techniques can help you sort your arrays according to an alphabet, numbers, in descending order, etc.

Sorting Methods

The sort() method sorts all array objects by alphabet - starting with A, and finishing with Z. This can be useful when making lists which require an alphabetical order of items:

Example
var cars = ["Peugeot", "Mercedes", "BMW", "Audi"];
cars.sort(); // Sorting the elements of cars

You can also use sort() to sort array JavaScript code contains that is written in a random order:

Example
var points = [30, 200, 2, 3, 15, 10];
points.sort((x, y) => { return 0.5 - Math.random() });

The reverse() method is very similar to sort(), as it is used to sort JavaScript array objects. However, it produces results in a reversed alphabetical order. It creates a descending order. In this case, the list starts with objects named Z and finishes with A:

Example
var cars = ["Peugeot", "Audi", "BMW", "Mercedes"];
cars.sort();            // Sorting the elements of cars
cars.reverse();         // Reversing the order of the elements

Comparing Elements

The sort() function reads values as textual data (strings). A string like "30" will be read as higher than "200" because of its first character: "3" is bigger than "2". Therefore, you will get wrong answers in your list. This problem can be solved using a compare() function:

Example
var point = [30, 200, 2, 3, 15, 10];
point.sort((x, y) => { return x - y });

The same method applies for sorting descending arrays:

Example
var point = [30, 200, 2, 3, 15, 10];
point.sort((x, y) => { return y - x });

When specifying a different sorting order, you should also use the compare function. It will bring back one of three values: a positive, negative or a zero:

Example
(x, y) => { return x - y }

In the example below, when 20 and 50 are compared, the method sort() is calling the function compare (20,50). Then, a calculation of 20-50 happens, and the answer is -30 (a negative value). Now, the sort JavaScript function will proceed with array sort with the lower value being 20 rather than 50:

Example
var points = [20, 50, 2, 4, 15, 10];
document.getElementById("test").innerHTML = points; 

function sortAlphabetically() {
 points.sort();
 document.getElementById("test").innerHTML = points;
}
function sortNumerically() {
 points.sort((a, b) => { return a - b });
 document.getElementById("test").innerHTML = points;
}

Finding Specified Values

Currently, there are no integrated functions for locating the minimum or maximum values of the array. However, you can solve this issue by obtaining the index of the lowest and the highest value in a sorted array. Then, you will be able to create ascending or descending lists. You can see both kinds created in the code examples below:

Example
var points = [30, 200, 2, 3, 15, 10];
points.sort((x, y) => { return x - y });
Example
var points = [30, 200, 2, 3, 15, 10];
points.sort((x, y) => { return y - x });

Math.max()

When trying to find the highest number in the whole array, you can use the Math.max.apply. This way, you don't have to use the numeric JavaScript sort array function to sort out the whole list. The function will return only the highest number:

Example
function mArrayMax(ar) {
    return Math.max.apply(null, ar);
}

Math.min()

Similarly to Math.max() method, you can locate the lowest number in the whole array using Math.min() method. This will only return the lowest number in the array:

Example
function mArrayMin(ar) {
    return Math.min.apply(null, ar);
}

Custom Min/Max Methods

The least time-consuming way is to use a JS array sorting method which is, let's say, homemade. Each value is compared with the highest value located in this while loop.Check out the possibilities that arise:

Example
function mArrayMax(ar) {
    var length = ar.length
    var maxim = -Infinity;
    while (length--) {
        if (ar[length] > maxim) {
            maxim = ar[length];
        }
    }
    return maxim;
}

Each value is compared with the lowest value located in this loop:

Example
function mArrayMin(ar) {
    var length = ar.length
    var minim = Infinity;
    while (length--) {
        if (ar[len] < minim) {
            minim = ar[length];
        }
    }
    return minim;
}

Sorting Object Arrays

In JavaScript, an array often has objects, like it is shown in the example below:

Example
var car = [
  { type: "Audi", year: 2017 },
  { type: "Toyota", year: 2009 },
  { type: "Mercedes", year: 2011 },
];

The method sort() can be used even when the objects have other datatype properties. To fix the problem, we can use the compare function:

Example
cars.sort((x, y) => { return x.year - y.year });

Working with string properties is a bit more work, but still manageable:

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

JavaScript Sort Array: Summary

  • Sort array JavaScript methods can help you with sorting arrays in alphabetical, reverse, random, numerical, descending and ascending order.
  • Array sort function sort() is the one you will use the most.
  • JavaScript sort array techniques are very helpful when you need to sort out a list or find the highest or lowest value.
What Is JavaScript Used For?
Tutorial
Introduction
Output
Syntax
Comment
Commands
Operators
Comparison and Logical Operators
Data Types
Math.random()
Type Conversion
Function Definitions
Events
Objects
Object Properties
Prototype
Array
Sorting Arrays
Strings
Numbers
Number Format
Math Object
Onclick Event
Date
Date Formats
Scope
Regular Expressions
Reserved Words
Common Mistakes
Performance
Forms
Form Validation
Window: The Browser Object Model
Popup Boxes
Cookies
JSON
AJAX Introduction
AJAX Form
Automatic File Download
Functions
Array Methods
String Methods
Date Methods
Timing Events
Cheat Sheet
JavaScript in HTML
HTML DOM Methods
HTML DOM Changing HTML
HTML DOM Animation
HTML DOM EventListener
HTML DOM Navigation
HTML DOM NodeList
HTML DOM Element Nodes
Array Functions
Boolean
Calling a Function
Date Functions
Global Objects
Input Text
Operator
Statements
String Functions
Math
Math.random
Number
RegEx
alert
array.filter
array.length
array.map
array.reduce
array.push
array.sort
break and continue
className
confirm
decodeURIComponent
for
forEach
if
indexOf
innerHTML
location.reload
number.toString
onclick
onload
parseInt
prompt
replace
setAttribute
setInterval
setTimeout
slice
splice
string.includes
string.indexOf
string.split
style.display
submit
substr
substring
switch
test
throw, try and catch
toLowerCase
toUpperCase
use strict
while
window.history
window.location
window.navigator
window.screen