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