JavaScript ES6 – Array sort method

The JavaScript sort() method sorts the elements of an array and returns the sorted array. The default sort order is ascending, but you can also sort array in descending order.

Think of JavaScript array sort() method as: “I want to sort an array in ascending or descending order.”

array sort() parameters

JavaScript array sort() method consists of following parameters:

  • a – The first comparison element
  • b – The second comparison element

Let’s see an example on how to use JavaScript array sort() method:

const arr = [23, 12, 15, 20];
const sorted = arr.sort();
console.log(sorted);

// OUTPUT
// 0: 12
// 1: 15
// 2: 20
// 3: 23

array sort() descending order

Let’s see how we can use sort() methods to sort an array in descending order.

const arr = [23, 12, 15, 20];
const sorted = arr.sort((a, b) => a > b ? -1 : 1);
console.log(sorted);

// OUTPUT
// [23, 20, 15, 12]

array sort() ascending order

Let’s see how we can use sort() methods to sort an array in ascending order.

const arr = [23, 12, 15, 20];
const sorted = arr.sort((a, b) => a > b ? 1 : -1);
console.log(sorted);

// OUTPUT
// [12, 15, 20, 23]

sort() method with objects

How to use JavaScript sort() method to sort object array? To sort objects in ascending or descending order we use sort() method the same way it’s used on an array.

Let’s see an example how to sort an object.

const obj = [
  { name: 'John', age: 21 },
  { name: 'Bob', age: 37 },
  { name: 'Justing', age: 45 },
  { name: 'Mary', age: 23 }
];

const sorted = obj.sort((a, b) => a.name > b.name ? -1 : 1);
console.log(sorted);

// OUTPUT
// {name: 'Mary', age: 23}
// {name: 'Justing', age: 45}
// {name: 'John', age: 21}
// {name: 'Bob', age: 37}

In above example we are sorting the object by obj.name in descending order. We can sort the object by obj.age the same way obj.sort((a, b) => a.age > b.age ? -1 : 1).

You may ask how to sort the object in ascending order? To sort object in ascending order we have to make sure we are the right condition on sort() parameters. a.name > b.name ? 1 : -1.

array sort() usage and tips

  • Use sort() method to sort array or objects in ascending or descending order
  • The sort() methods perform sorting in ascending order by default
  • When sorting numbers it only sorts values that are not Infinity or NaN

%d bloggers like this: