EN
JavaScript - sort two dimensional array by column value
0
points
In this article, we would like to show you how to sort a two-dimensional array by column value in JavaScript.
Practical example
In this example, we create a custom compare function to sort a 2D array by first column value.
// ONLINE-RUNNER:browser;
const array = [
[2, 'a'],
[1, 'c'],
[4, 'b'],
[3, 'd'],
];
const compareFunction = (a, b) => {
if (a[0] === b[0]) {
return 0;
} else {
return a[0] < b[0] ? -1 : 1;
}
};
array.sort(compareFunction);
console.log(JSON.stringify(array)); // [[1,"c"],[2,"a"],[3,"d"],[4,"b"]]
By second column value:
// ONLINE-RUNNER:browser;
const array = [
[2, 'a'],
[1, 'c'],
[4, 'b'],
[3, 'd'],
];
const compareFunction = (a, b) => {
if (a[1] === b[1]) {
return 0;
} else {
return a[1] < b[1] ? -1 : 1;
}
};
array.sort(compareFunction);
console.log(JSON.stringify(array)); // [[2,"a"],[4,"b"],[1,"c"],[3,"d"]]