How to Sort Arrays in JavaScript with sort() method

If you are dealing with arrays of data, then it is always better to have the data in a sorted manner. JavaScript’s sort() method sorts the items in array in alphabetic or numeric order.

const cars = ['BMW', 'Jaguar', 'Audi', 'Tesla', 'Ferrari'];

console.log(cars.sort()); 
//["Audi", "BMW", "Ferrari", "Jaguar", "Tesla"]

The sort() method does its default sorting based on alphabetic or numeric order

For numbers, the sort() method sorts values as strings. If numbers are sorted as strings, then it will produce incorrect results like “8” is greater than “55”, as “8” is greater than “5” and “-52” is greater than “-206” as “5” is greater than “2”.

const numbers = [50, -22, 8, -12, 30];

numbers.sort();

console.log(numbers); // [-12, -22, 30, 50, 8]

You can see here, “-22” is greater than “-12” as “2” is greater than “1” and “8” is greater than “50” as “8” is greater than “5”, and thus all are incorrect results. We will see in a moment how to fix this sorting issue and provide correct results.

Sometimes we may need to sort the array based on some parameter or some condition. Array’s sort() method accepts a callback function called compare function where you can define your compare logic.

The compare function takes two parameters and executes the compare function for each two items in array. You can use those two items and do your comparing. The comparing function returns three possible values i.e. positive, zero or negative.

  • If compare function returns negative value, first item is smaller than second item.
  • If it returns zero, both items are equal.
  • If it returns positive value, first item is greater than second item.
const numbers = [50, -22, 8, -12, 30];

numbers.sort((item1, item2) => {
    return item1 > item2 ? 1 : -1;
});

console.log(numbers); //[-22, -12, 8, 30, 50]

Sorting Array containing objects

const students = [
    {name: 'Amitav', id: 32},
    {name: 'Ranjit', id: 19},
    {name: 'Rohit', id: 43},
    {name: 'Suraj', id: 15}
];

students.sort((obj1, obj2) => {
   return obj1.id > obj2.id ? 1 : -1;
});

console.log(students);

Output:

[
    {name: 'Suraj', id: 15},
    {name: 'Ranjit', id: 19},
    {name: 'Amitav', id: 32},
    {name: 'Rohit', id: 43},
 ]

Now you can define your own sorting method based on the object that you want to sort.

Leave a Reply

Your email address will not be published. Required fields are marked *