How to sort an array | JavaScript

/ #JavaScript


Sorting an array alphabetically or numerically is something we often do as programmers, but how do you do this using JavaScript?

Sort alphabetically

// Define an array
var animals = ["Tiger", "Giraffe", "Lion", "Elephant"];

// Sort it
animals.sort();

The new array will now be ['Elephant', 'Giraffe', 'Lion', 'Tiger'].

Reversed alphabetically

But what if you want to sort it in the reversed order? If you just run ".reverse()" on the array, it will just be reversed and not by letter. To fix this, we need to run ".sort()" first.

// Define an array
var animals = ["Tiger", "Giraffe", "Lion", "Elephant"];

// Sort it
animals.sort();
animals.reverse();

The new array will now be ['Tiger', 'Lion', 'Giraffe', 'Elephant'].

Sort numerically

Sorting an array based on the numerical value is a little bit more tricky.

// Define an array
var numbers = [10, 4, 13, 1, 100];

// Sort it
numbers.sort(function(a, b) {return a - b});

As you can see, we still use the .sort() function from JavaScript, but we pass in a function as a parameter.

The new array will now be: [1, 4, 10, 13, 100].

Comments

No comments yet...

Add comment

Newsletter

Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.