How to Sort an Array in Javascript

In this tutorial, you will learn how to sort an array in javascript. As a web developer, I think it is extremely important that you provide your users the ability to sort the data in ascending or descending order. It is common to have such data in the form of an array so that we can easily manipulate the order of items in it.

In javascript, we have 2 methods to change the order of items in an array, sort() and reverse().  The sort() method will sort all the items in the array in ascending order.

On the other hand, the reverse() method will not sort the items in descending order but will just reverse the order of the items.  So we need a combination of sort() and reverse() methods to sort the items in descending order.

This sorting approach will only work if your array contains either only strings or only numbers.

In the following example, we have one global array users.  There are also 2 buttons, Ascending and Descending.  We will sort the items in the array depending upon which button is clicked by the user and after that, we will display the items on the screen.  Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, button, and ul). The div element is just a wrapper for the rest of the elements.
  • The first button element has “Ascending” and the second button element has “Descending” as inner text.
  • The ul element is empty for now since we will populate it dynamically using javascript.
  • We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style.css">
  <title>Document</title>
</head>
<body>
  
  <div>
    <button id="btnAsc">Ascending</button>
    <button id="btnDesc">Descending</button>
    <ul></ul>
  </div>

  <script src="script.js"></script>
</body>
</html>
div {
    width: 15%;
    margin: auto;
}

button {
    padding: 10px;
}

li {
    font-size: 20px;
    margin-left: -30px;
    font-weight: bold;
    list-style: none;    
}

Javascript

  • We have a global variable users and it holds an array of strings.
  • We have the addUsers() method which is responsible for populating our ul element.
  • In addUsers() method, we are simply looping through the users array and creating a template string with a bunch of li elements.
  • We are displaying that list in the ul element.
  • We have selected both the button elements by their ids using the document.querySelector() method and stored them in btnAsc and btnDesc variables respectively.
  • We have attached the click event listener to the button elements.
  • In the event handler function of the ascending button, we are sorting the array in ascending order using the sort() method and updating the list of users by calling addUsers() method.
  • In the event handler function of the descending button, we are sorting the array in ascending order using the sort() method and then reversing the order using the reverse() method. This will change the order from ascending to descending.  Finally, we are calling addUsers() method to update the list of the users.
let users = ['Peter', 'Marks', 'Cathy', 'James', 'Ronald'];

function addUsers(){
    let template = users.map(user => `<li>${user}</li>`).join('\n');
    document.querySelector('ul').innerHTML = template;
}

addUsers();

let btnAsc = document.querySelector('#btnAsc');
let btnDesc = document.querySelector('#btnDesc');

btnAsc.addEventListener('click', () =>{
    users.sort();
    addUsers();
});

btnDesc.addEventListener('click', () =>{
    users.sort();
    users.reverse();
    addUsers();
});