EN
JavaScript - sort array by multiple numeric fields (descending 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:
xxxxxxxxxx
1
// sort by 2 properties
2
3
array.sort((a, b) => b.property1 - a.property1 || b.property2 - a.property2);
or:
xxxxxxxxxx
1
// sort by 3 properties
2
3
array.sort((a, b) => b.property1 - a.property1 ||
4
b.property2 - a.property2 ||
5
b.property3 - a.property3 );
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 (...
).
xxxxxxxxxx
1
const sortArray = (array, getters) => {
2
if (getters.length === 0) {
3
throw new Error('Getters are not defined.');
4
}
5
array.sort((a, b) => {
6
for (let i = 0; i < getters.length; ++i) {
7
const getter = getters[0];
8
const result = getter(b) - getter(a);
9
if (result !== 0) {
10
return result;
11
}
12
}
13
return 0;
14
});
15
return array;
16
};
17
18
19
// Usage example
20
21
const array = [
22
{ number: 2, type: 1, order: 2 },
23
{ number: 1, type: 1, order: 2 },
24
{ number: 2, type: 2, order: 1 },
25
{ number: 1, type: 2, order: 1 }
26
];
27
28
sortArray(array, (item) => item.number, (item) => item.type, (item) => item.order);
29
30
console.log(JSON.stringify(array, null, 4));