How does one sort a multi dimensional array by multiple columns in JavaScript?
var arr = [27, 2, 4, 13]
arr.sort();
sets arr as [13, 2, 27, 4], because arrays are sorted as strings by default in JavaScript
arr.sort(function (a, b) {
return a - b;
});
sets arr as [2, 4, 13, 27] sorting numerically forward.
arr.sort(function (a, b) {
return b - a;
});
sets arr as [27, 13, 4, 2] sorting numerically in reverse.
var marr = [[]];
marr.shift();
marr.push(["frog", 4, 27, 13]);
marr.push(["frog", 11, 5, 12]);
marr.push(["cat", 16, 3, 5]);
marr.push(["dog", 11, 7, 21]);
marr.push(["cat", 16, 21, 6]);
marr.push(["dog", 10, 280, 5]);
marr.push(["dog", 10, 32, 5]);
marr.sort();
sets marr as follows, sorting array rows, by column in order as strings..
["cat", 16, 21, 6]
["cat", 16, 3, 5]
["dog", 10, 280, 5]
["dog", 10, 32, 5]
["dog", 11, 7, 21]
["frog", 11, 5, 12]
["frog", 4, 27, 13]
calling sort by column allows sorting by a single column. sort row by 3rd column as number..
marr.sort(function (a, b) {
return a[2] - b[2];
});
["cat", 16, 3, 5]
["frog", 11, 5, 12]
["dog", 11, 7, 21]
["cat", 16, 21, 6]
["frog", 4, 27, 13]
["dog", 10, 32, 5]
["dog", 10, 280, 5]
then sort 4th column in reverse as number..
marr.sort(function (a, b) {
return b[3] - a[3];
});
["dog", 11, 7, 21]
["frog", 4, 27, 13]
["frog", 11, 5, 12]
["cat", 16, 21, 6]
["cat", 16, 3, 5]
["dog", 10, 32, 5]
["dog", 10, 280, 5]
then sort 2nd column ascending as number
marr.sort(function (a, b) {
return a[1] - b[1];
});
["frog", 4, 27, 13]
["dog", 10, 32, 5]
["dog", 10, 280, 5]
["dog", 11, 7, 21]
["frog", 11, 5, 12]
["cat", 16, 21, 6]
["cat", 16, 3, 5]
notice each time you sort, prior order is maintained where new column is a match to a consecutive row.
Now you can roll in alpha sorting of the first column
// asc
marr.sort(function (a, b) {
return (a[0] < b[0]) ? -1 : 1;
});
["cat", 16, 21, 6]
["cat", 16, 3, 5]
["dog", 10, 32, 5]
["dog", 10, 280, 5]
["dog", 11, 7, 21]
["frog", 4, 27, 13]
["frog", 11, 5, 12]
// desc
marr.sort(function (a, b) {
return (a[0] > b[0]) ? -1 : 1;
});
["frog", 4, 27, 13]
["frog", 11, 5, 12]
["dog", 10, 32, 5]
["dog", 10, 280, 5]
["dog", 11, 7, 21]
["cat", 16, 21, 6]
["cat", 16, 3, 5]
sort all the numeric columns in a desc loop : 4, 3, 2 then sort the 1st column asc as string
for (var colid = 3; colid > 0; colid--) {
marr.sort(function (a, b) {
return (b[colid] - a[colid]);
});
}
// 1st row as string asc
marr.sort(function (a, b) {
return (a[0] < b[0]) ? -1 : 1;
});
["cat", 16, 21, 6]
["cat", 16, 3, 5]
["dog", 11, 7, 21]
["dog", 10, 280, 5]
["dog", 10, 32, 5]
["frog", 11, 5, 12]
["frog", 4, 27, 13]
combine these sorts.. in a more logical way, in order of what column you want to sort & how you want it sorted first
// c1 asc, c2 desc, c3 asc, c4 asc
marr.sort(function (a, b) {
return (a[0] < b[0]) ? -1 : (a[0] == b[0]) ?
(b[1] - a[1]) || (a[2] - b[2]) || (a[3] - b[3]) : 1;
});
["cat", 16, 3, 5]
["cat", 16, 21, 6]
["dog", 11, 7, 21]
["dog", 10, 32, 5]
["dog", 10, 280, 5]
["frog", 11, 5, 12]
["frog", 4, 27, 13]
The array literal []
is preferred over new Array
. The notation {0,4,3,1}
is not valid and should be [0,4,3,1]
.
Is there a need for reinventing the wheel? Two arrays can be joined using:
originalArray = originalArray.concat(addArray);
Elements can be appended to the end using:
array.push(element);
Arrays have a method for sorting the array. By default, it's sorted numerically:
// sort elements numerically
var array = [1, 3, 2];
array.sort(); // array becomes [1, 2, 3]
Arrays can be reversed as well. Continuing the previous example:
array = array.reverse(); //yields [3, 2, 1]
To provide custom sorting, you can pass the optional function argument to array.sort()
:
array = [];
array[0] = [1, "first element"];
array[1] = [3, "second element"];
array[2] = [2, "third element"];
array.sort(function (element_a, element_b) {
return element_a[0] - element_b[0];
});
/** array becomes (in order):
* [1, "first element"]
* [2, "third element"]
* [3, "second element"]
*/
Elements will retain their position if the element equals an other element. Using this, you can combine multiple sorting algoritms. You must apply your sorting preferences in reverse order since the last sort has priority over previous ones. To sort the below array by the first column (descending order) and then the second column (ascending order):
array = [];
array.push([1, 2, 4]);
array.push([1, 3, 3]);
array.push([2, 1, 3]);
array.push([1, 2, 3]);
// sort on second column
array.sort(function (element_a, element_b) {
return element_a[1] - element_b[1];
});
// sort on first column, reverse sort
array.sort(function (element_a, element_b) {
return element_b[0] - element_a[0];
});
/** result (note, 3rd column is not sorted, so the order of row 2+3 is preserved)
* [2, 1, 3]
* [1, 2, 4] (row 2)
* [1, 2, 3] (row 3)
* [1, 3, 3]
*/
To sort latin strings (i.e. English, German, Dutch), use String.localeCompare
:
array.sort(function (element_a, element_b) {
return element_a.localeCompare(element_b);
});
To sort date's from the Date
object, use their milliseconds representation:
array.sort(function (element_a, element_b) {
return element_a.getTime() - element_b.getTime();
});
You could apply this sort function to all kind of data, just follow the rules:
x
is the result from comparing two values which should be returned by a function passed to array.sort
.
x < 0
:element_a
should come beforeelement_b
x = 0
:element_a
andelement_b
are equal, the elements are not swappedx > 0
:element_a
should come afterelement_b
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 ]