Advertisement
  1. Code
  2. JavaScript

Sorting Values With JavaScript

Scroll to top
Read Time: 6 min

If you already understand the basics of JavaScript arrays, it's time to take your skills to the next level with more advanced topics. In this series of tutorials, you'll explore intermediate-level topics for programming with arrays in JavaScript.

Sorting arrays is one of the most common tasks you'll do when programming in JavaScript. Therefore, as a JavaScript programmer, it’s essential that you learn how to correctly sort an array because you’ll be doing it a lot in real-life projects. And the wrong sorting technique can really slow your app down!

In the past, web developers had to use third-party libraries like jQuery and write large volumes of code just to sort values in a list collection. Fortunately, JavaScript has evolved tremendously since then. Today, you can sort a JavaScript array with thousands of values in just one line of code, without using any third-party libraries.

In this article, I’ll show you how to sort both simple and complex array collections in JavaScript. We’ll be using the JavaScript sort() method to sort:

  • an array of numbers
  • an array of strings
  • an array of complex objects
    • by name (string)
    • by ID (number)
    • by date of birth (date)

By the end of this tutorial, you should have a thorough understanding of how JavaScript's sort() method works and how to use it to sort an array of numbers, strings, and objects.

JavaScript sort() Method

The JavaScript sort() method is one of the most useful and commonly used array methods in JavaScript. It allows you to quickly and easily sort an array of data elements in ascending or descending order.

You can use the method to sort an array of numbers, strings, dates, or even objects. The sort() method works by taking an array of elements and sorting them according to some criteria. The criteria can be a function, a comparison operator, or an array of values.

Sorting an Array of Numbers

Sorting an array of numbers is pretty straightforward with the sort method:

1
let numbers = [12, 88, 57, 99, 03, 01, 83, 21]
2
console.log(numbers.sort())
3
4
// output [1, 12, 21, 3, 57, 83, 88, 99]

In the code above, the sort() method sorted the numbers in ascending order, which is the default mode.

You can also sort the numbers backwards (that is, in descending order). To achieve that, you’ll need to create the following custom sort function:

1
function desc(a, b) {
2
 return b - a
3
}

This function takes in two parameters (a and b) which represent two values to be sorted. If it returns a positive number, the sort() method will understand that b should be sorted before a. If it returns a negative number, then sort() will understand that a should come before b. This function will return a positive number if b > a, meaning b will come before a if a is less than b

1
console.log(numbers.sort(desc))
2
// output [99, 88, 83, 57, 21, 12, 3, 1]

Up next is how to sort an array of strings.

Sorting an Array of Strings in Java Script

Sorting string values is equally straightforward:

1
let names = ["Sam", "Koe", "Eke", "Victor", "Adam"]
2
console.log(names.sort())
3
4
// output ["Adam", "Eke", "Koe", "Sam", "Victor"]

Here’s the function for sorting the same strings in descending order:

1
function descString(a, b) {
2
    return b.localeCompare(a);
3
}

If the second name comes after the first alphabetically, we return 1 from the function, meaning the second name will come first in the sorted array. Otherwise, we return -1, or 0 if both are equal.

Now, if you run the sort method on the names array, with desc as its argument, you get a different output:

1
console.log(names.sort(descString))
2
3
// ["Victor", "Sam", "Koe", "Eke", "Adam"]

Sorting an Array of Complex Objects in JavaScript

So far, we’ve only sorted simple values like strings and numbers. You can also sort an array of objects using the sort() method. Let’s see how in the following sections.

Sorting Objects by Name (a String Property)

Here we have a people array with multiple person objects. Each object consists of the id, name, and dob properties:

1
const people = [
2
  {id: 15, name: "Blessing", dob: '1999-04-09'},
3
  {id: 17, name: "Aladdin", dob: '1989-06-21'},
4
  {id: 54, name: "Mark", dob: '1985-01-08'},
5
  {id: 29, name: "John", dob: '1992-11-09'},
6
  {id: 15, name: "Prince", dob: '2001-09-09'}
7
]

To sort this array by the name property, we have to create and pass a custom sort function to the sort method:

1
students.sort(byName)

This byName custom sort function will take in two objects each time and compare both of their name properties to see which is greater (i.e. which comes first alphabetically):

1
function byName(a, b) {
2
    return a.name.localeCompare(b.name);
3
}

Now, if you run the code again, you’ll get this:

1
[
2
  {id: 17, name: "Aladdin", dob: '1989-06-21'},
3
  {id: 15, name: "Blessing", dob: '1999-04-09'},
4
  {id: 29, name: "John", dob: '1992-11-09'},
5
  {id: 54, name: "Mark", dob: '1985-01-08'},
6
  {id: 32, name: "Prince", dob: '2001-09-09'}
7
]

Sorting by ID (a Number Property)

In the previous example, we were sorting by the names, which were strings. In this example, we’ll be sorting by the ID properties of each object (numbers).

For this, we can make use of the following function:

1
function byID(a, b) {
2
  return parseInt(a.id) - parseInt(b.id)
3
}

In the function, we use parseInt() to make sure the value is a number, and then we subtract both numbers to get a negative, positive, or zero value. With this function, you can sort any array of objects by a common numeric property. 

1
console.log(students.sort(byID))
2
/*

3
[

4
  {id: 15, name: "Blessing", dob: '1999-04-09'},

5
  {id: 17, name: "Aladdin", dob: '1989-06-21'},

6
  {id: 29, name: "John", dob: '1992-11-09'},

7
  {id: 32, name: "Prince", dob: '2001-09-09'}

8
  {id: 54, name: "Mark", dob: '1985-01-08'},

9
]

10
*/

Sorting by Date

Let’s say you want to build an application that allows users to download a list of names from the database, but you want the names to be arranged in chronological order, based on the date of birth (from the oldest to the youngest).

This function sorts the date of birth chronologically by year, month, and then day.

1
function byDate(a, b) {
2
   return new Date(a.dob).valueOf() - new Date(b.dob).valueOf()
3
}

The Date().valueOf() call returns a timestamp for each date. We then do the same subtraction as in the previous examples to determine the order.

Demo:

1
console.log(students.sort(byDate))
2
3
/*

4
[

5
  {id: 54, name: "Mark", dob: '1985-01-08'},

6
  {id: 17, name: "Aladdin", dob: '1989-06-21'},

7
  {id: 29, name: "John", dob: '1992-11-09'},

8
  {id: 15, name: "Blessing", dob: '1999-04-09'},

9
  {id: 32, name: "Prince", dob: '2001-09-09'}

10
]

11
*/

This particular method can come in quite handy in situations involving the order of dates, like an application that determines who qualifies for a pension or some other age-related benefit.

Conclusion

Overall, sorting elements in JavaScript is quite straightforward when using the various built-in methods. Whether you need to sort an array of numbers, strings, objects, or dates, there is a method that can easily do the job. With the help of these methods, you can quickly and easily sort any data in your JavaScript application.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.