Languages
[Edit]
EN

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

0 points
Created by:
mkrieger1
726

In this article, we would like to show you how to sort an array by multiple numeric fields in JavaScript.

Quick solution:

// sort by 2 properties

array.sort((a, b) => a.property1 - b.property1 || a.property2 - b.property2);

or:

// sort by 3 properties

array.sort((a, b) => a.property1 - b.property1 ||
                     a.property2 - b.property2 ||
                     a.property3 - b.property3 );

 

Reusable arrow function

In this example, we present a reusable arrow function that sorts multiple numeric fields in ascending order by multiple getters provided by the spread syntax (...).

// ONLINE-RUNNER:browser;

const sortArray = (array, ...getters) => {
    if (getters.length === 0) {
        throw new Error('Getters are not defined.');
    }
    array.sort((a, b) => {
        for (let i = 0; i < getters.length; ++i) {
            const getter = getters[0];
            const result = getter(a) - getter(b);
            if (result !== 0) {
                return result;
            }
        }
        return 0;
    });
    return array;
};


// Usage example

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

sortArray(array, (item) => item.number, (item) => item.type, (item) => item.order);

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

See also

  1. JavaScript - sort array by multiple numeric fields (descending order)

References

  1. Spread syntax (...) - 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