Languages
[Edit]
EN

JavaScript - how to sort array of objects?

12 points
Created by:
Marcin
2447

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

 

Hey ūüĎč
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.