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.
Contents
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:
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:
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:
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:
var point = [30, 200, 2, 3, 15, 10];
point.sort((x, y) => { return x - y });
The same method applies for sorting descending arrays:
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:
(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:
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;
}
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
- The price matches the quality
- Suitable for learners ranging from beginner to advanced
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
- A wide range of learning programs
- University-level courses
- Easy to navigate
- Verified certificates
- Free learning track available
- University-level courses
- Suitable for enterprises
- Verified certificates of completion
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:
var points = [30, 200, 2, 3, 15, 10];
points.sort((x, y) => { return x - y });
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:
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:
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:
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:
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:
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:
Working with string properties is a bit more work, but still manageable:
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.