Sorting multidimensional array
suggest changeGiven the following array
const array = [
["key1", 10],
["key2", 3],
["key3", 40],
["key4", 20]
];
You can sort it by the number at index 1. The arrow function below is an alternative to the function above, not a second sort.
array.sort(function(a, b) {
return a[1] - b[1];
})
array.sort((a,b) => a[1] - b[1]);
This will output
[
["key2", 3],
["key1", 10],
["key4", 20],
["key3", 40]
]
sort changes the array and returns it. Methods such as map, filter, and slice return a new array. toSorted returns a sorted copy.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents