EN
JavaScript - sort array by two numeric fields (descending order)
0 points
In this article, we would like to show you how to sort an array by two numeric fields in descending order working with JavaScript.
Quick solution:
xxxxxxxxxx
1
array.sort((a, b) => b.number - a.number || b.type - a.type);
In this example, we use sort()
method with a custom compare function to sort array
by number
property value, then by type
, both in descending order.
xxxxxxxxxx
1
const array = [
2
{ number: 2, type: 1 },
3
{ number: 1, type: 1 },
4
{ number: 2, type: 2 },
5
{ number: 1, type: 2 },
6
];
7
8
array.sort((a, b) => b.number - a.number || b.type - a.type);
9
10
console.log(JSON.stringify(array, null, 4));
xxxxxxxxxx
1
const sortArray = (array, property1, property2) => {
2
return array.sort((a, b) => b[property1] - a[property1] || b[property2] - a[property2]);
3
};
4
5
6
// Usage example
7
8
const array = [
9
{ number: 2, type: 1 },
10
{ number: 1, type: 1 },
11
{ number: 2, type: 2 },
12
{ number: 1, type: 2 },
13
];
14
15
sortArray(array, 'number', 'type');
16
17
console.log(JSON.stringify(array, null, 4));
18