Home

Sort array of numbers/strings in ascending or descending order.

JavaScript provides a sort method on every array(using prototype). Using the sort method you can sort arrays simple without having to known any sorting algorithms. In this article I will walk you through various examples on how to sort arrays.

Syntax of sort method

arr.sort([compareFunction]);

You can provide compareFunction to the sort method to customise the sorting procedure, even though it is optional.

compareFunction: A compareFunction takes two arguments, which are the array elements. It should return either 1,-1, or 0

We better learn by examples, right?

Let's assume a array of users

const users = [
  {
    firstName: 'John',
    lastName: 'Doe',
    age: 38,
  },
  {
    firstName: 'Joe',
    lastName: 'Lane',
    age: 27,
  },
  {
    firstName: 'Stephen',
    lastName: 'Hobbs',
    age: 49,
  },
];

Sort by age

Ascending Order

const sorted = users.sort((user1, user2) => user1.age - user2.age);

Descending Order

const sorted = users.sort((user1, user2) => user2.age - user1.age);

Sort by firstName

Ascending Order

const sorted = users.sort(function(user1, user2) {
  if (user1.firstName < user2.firstName) return -1;
  if (user1.firstName > user2.firstName) return 1;
  return 0;
});

Descending Order

const sorted = users.sort(function(user1, user2) {
  if (user1.firstName > user2.firstName) return -1;
  if (user1.firstName < user2.firstName) return 1;
  return 0;
});

Resources

Sort on MDN



Last Updated on

Next Post: Rules vs Guidelines →

Comments