Languages
[Edit]
EN

JavaScript - how to sort array of objects?

12 points
Created by:
Marcin
17380

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
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join