EN
JavaScript - sort array by multiple numeric fields (ascending order)
0
points
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));