How to Sort an Array of Objects in JavaScript?

To sort an array in JavaScript we generally use the built-in function sort(). But there are two problems with the sort() function. First, it sorts the array in alphabetical order, and second, it cannot directly sort an array of objects.

Sorting in alphabetical order means that the array elements are first converted into strings and then sorted accordingly. It means that ‘Apple’ comes before ‘Banana’.

But if you apply the sort() function directly to an array of numbers, it might give you unexpected results. Because if we sort numbers as strings then “20” is bigger than “100” as “2” is bigger than “1”. Therefore, in the sorted array, 100 will come before 20.

See the following example where we are trying to sort a numbers array in ascending order:

var numbers = [40, 200, 100, 30, 25];
numbers.sort();

console.log(numbers);

Output:

// Array after sorting(Incorrect result)
[100, 200, 25, 30, 40]

As you can see from the above example, the numbers array isn’t sorted at all after applying the sort() function on it. This is a serious problem. Isn’t it?

But no worries. The sort() function itself provides a solution for this problem. The sort() function lets you pass a custom function as an argument where we can write our own custom logic to sort the array of numbers as well as an array of objects.

Let’s first try to solve the above problem with a custom compare() function:

function compare(a, b){
     if(a<b){
         return -1;
     }else if(a>b){
         return 1;
     }else{
         return 0;
     }
 }
 
var numbers = [40, 200, 100, 30, 25];
numbers.sort(compare);
    
console.log(numbers);

Output:

// Array after sorting(Correct result)
[25, 30, 40, 100, 200]

The array is now sorted correctly. But how does it work?

Well, when we are writing a custom compare function it should return a negative, positive, or a zero value.

The sort() function sends two values at a time to the compare() function as an argument and sorts them according to the value returned by the compare() function.

If the compare() function returns a negative value, a is sorted before b.

If the compare() function returns a positive value, a is sorted after b.

If the compare() function returns a zero value, no changes are done.

This is exactly how the above numbers array is sorted with the compare() function. The similar concept we are going to use to solve our original problem of sorting an array of objects.


Sort an Array of Objects

Let’s say we have an array of objects where each object contains the data of a student and we want to sort the student array according to their age.

As I previously said we will write our custom compare function to compare the age of the students. And this compare function will return a negative, positive, or a zero value.

See the code below:

let students = [
    {
        name: 'John',
        age: 22
    },
    {
        name: 'David',
        age: 24
    },
    {
        name: 'William',
        age: 19
    },
    {
        name: 'Thomas',
        age: 25
    }
];

function compare(a, b){
    if(a.age < b.age){
        return -1;
    }else if(a.age > b.age){
        return 1;
    }else{
        return 0;
    }
}

students.sort(compare);
console.log(students);

Output:

// students array after sorting by student's age
[ 
  { name: 'William', age: 19 },
  { name: 'John', age: 22 },
  { name: 'David', age: 24 },
  { name: 'Thomas', age: 25 }
]

Sort students array by student name:

Just like the student age, you can sort the students array by the student name also.

See the following code:

let students = [
    {
        name: 'John',
        age: 22
    },
    {
        name: 'David',
        age: 24
    },
    {
        name: 'William',
        age: 19
    },
    {
        name: 'Thomas',
        age: 25
    }
];

function compare(a, b){
    if(a.name.toLowerCase() < b.name.toLowerCase()){
        return -1;
    }else if(a.name.toLowerCase() > b.name.toLowerCase()){
        return 1;
    }else{
        return 0;
    }
}

students.sort(compare);
console.log(students);

Output:

// students array after sorting by student's name
[ 
  { name: 'David', age: 24 },
  { name: 'John', age: 22 },
  { name: 'Thomas', age: 25 },
  { name: 'William', age: 19 } 
]

Thanks for reading.

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

    View all posts