Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ‚̧ ūüíĽ
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

JavaScript - how to sort array of objects?

0 contributions
12 points

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

 

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey ūüĎč
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more