How to sort 2 dimensional array by column value?
Can any one help me sort a 2 dimensional Array in JavaScript?
It will have data in the following format:
[12, AAA]
[58, BBB]
[28, CCC]
[18, DDD]
It should look like this when sorted:
[12, AAA]
[18, DDD]
[28, CCC]
[58, BBB]
So basically, sorting by the first column.
Cheers
It's this simple:
var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']];
a.sort(sortFunction);
function sortFunction(a, b) {
if (a[0] === b[0]) {
return 0;
}
else {
return (a[0] < b[0]) ? -1 : 1;
}
}
I invite you to read the documentation.
If you want to sort by the second column, you can do this:
a.sort(compareSecondColumn);
function compareSecondColumn(a, b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] < b[1]) ? -1 : 1;
}
}
The best approach would be to use the following, as there may be repetitive values in the first column.
var arr = [[12, 'AAA'], [12, 'BBB'], [12, 'CCC'],[28, 'DDD'], [18, 'CCC'],[12, 'DDD'],[18, 'CCC'],[28, 'DDD'],[28, 'DDD'],[58, 'BBB'],[68, 'BBB'],[78, 'BBB']];
arr.sort(function(a,b) {
return a[0]-b[0]
});
try this
//WITH FIRST COLUMN
arr = arr.sort(function(a,b) {
return a[0] - b[0];
});
//WITH SECOND COLUMN
arr = arr.sort(function(a,b) {
return a[1] - b[1];
});
Note: Original answer used a greater than (>) instead of minus (-) which is what the comments are referring to as incorrect.
Using the arrow function, and sorting by the second string field
var a = [[12, 'CCC'], [58, 'AAA'], [57, 'DDD'], [28, 'CCC'],[18, 'BBB']];
a.sort((a, b) => a[1].localeCompare(b[1]));
console.log(a)