Languages
[Edit]
EN

JavaScript - sort array by two numeric fields (ascending order)

0 points
Created by:
Giles-Whittaker
739

In this article, we would like to show you how to sort an array by two numeric fields in ascending order working with JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

array.sort((a, b) => a.number - b.number || a.type - b.type);

 

Practical example

In this example, we use sort() method with a custom compare function to sort array by number property value, then by type, both in ascending order.

// ONLINE-RUNNER:browser;

const array = [
    { number: 2, type: 1 },
    { number: 1, type: 1 },
    { number: 2, type: 2 },
    { number: 1, type: 2 },
];

array.sort((a, b) => a.number - b.number || a.type - b.type);

console.log(JSON.stringify(array, null, 4));

Reusable arrow function

// ONLINE-RUNNER:browser;

const sortArray = (array, property1, property2) => {
    return array.sort((a, b) => a[property1] - b[property1] || a[property2] - b[property2]);
};


// Usage example

const array = [
    { number: 2, type: 1 },
    { number: 1, type: 1 },
    { number: 2, type: 2 },
    { number: 1, type: 2 },
];

sortArray(array, 'number', 'type');

console.log(JSON.stringify(array, null, 4));

See also

  1. JavaScript - sort array by multiple numeric fields

  2. JavaScript - sort array by two numeric fields (descending order)

References

  1. Array.prototype.sort() - JavaScript | MDN
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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