I\'ve been working on this problem all day without a good solution. Google has been little help as well. I have a script that needs to accept a two dimensional array with
There are already good answers to this question, would like to add a short functions to handle multiple key array sort inspired solution of https://stackoverflow.com/users/2279116/shinobi.
// sort function handle for multiple keys
const sortCols = (a, b, attrs) => Object.keys(attrs)
.reduce((diff, k) => diff == 0 ? attrs[k](a[k], b[k]) : diff, 0);
Let's take an following example
const array = [
[1, 'hello', 4],
[1, 'how', 3],
[2, 'are', 3],
[1, 'hello', 1],
[1, 'hello', 3]
];
array.sort((a, b) => sortCols(a, b, {
0: (a, b) => a - b,
1: (a, b) => a.localeCompare(b),
2: (a, b) => b - a
}))
The output would be following.
[ 1, "hello", 4 ]
[ 1, "hello", 3 ]
[ 1, "hello", 1 ]
[ 1, "how", 3 ]
[ 2, "are", 3 ]