Languages
[Edit]
EN

JavaScript - how to sort array of objects?

12 points
Created by:
Marcin
15710

1. Overview

In JavaScript it is possible to sort array of objects in following way.

2. Sorting array in ascending ordering

In this example objects are sorted from smallest to biggest age - Array sort (Array.prototype.sort) method with ascending ordering has been used.

// ONLINE-RUNNER:browser;

var array = [
  { name: 'John', age: 25 },
  { name: 'Kate', age: 32 },
  { name: 'Chris', age: 19 }
];

// sort by age operation asc order eg 1,2,3
array.sort(function(a, b) {
    return a.age - b.age;
});

console.log(array);

Output:

[
  { name: 'Chris', age: 19 },
  { name: 'John', age: 25 },
  { name: 'Kate', age: 32 }
]

Notes:

  • for a.age¬†- b.age¬†is ascending ordering critery -¬†from smallest to biggest value
  • using a.name - b.name we can order ascending by name

3. Sorting array in descending ordering

In this example objects are sorted from biggest to smallest age - Array sort (Array.prototype.sort) method with descending ordering has been used.

// ONLINE-RUNNER:browser;

var array = [
  { name: 'John', age: 25 },
  { name: 'Kate', age: 32 },
  { name: 'Chris', age: 19 }
];

// sort by age operation desc order eg 3,2,1
array.sort(function(a, b) {
    return b.age - a.age;
});

console.log(array);

Output:

[
  { name: 'Kate', age: 32 },
  { name: 'John', age: 25 },
  { name: 'Chris', age: 19 }
]

Notes:

  • for b.age¬†- a.age¬†is descending ordering critery -¬†from biggest to¬†smallest value
  • using b.name - a.name we can order descending by name

 

Native Advertising
50 000 ad impressions - 449$
ūüöÄ
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

‚̧ԳŹūüíĽ ūüôā

Join