Sort a Javascript 2d Array by Any Column Value
Sort a 2d Array by any column value.
// given the array
array = [
["Tiger Nixon", "Architect", "Edinburgh", "61", "2011/04/25"],
["Garrett Winters", "Accountant", "Tokyo", "63", "2011/07/25"],
["Ashton Cox", "Technical Author", "San Francisco", "66", "2009/01/12"],
["Cedric Kelly", "Javascript Developer", "Edinburgh", "22", "2012/03/29"],
["Airi Satou", "Accountant", "Tokyo", "33", "2008/11/28"],
["Brielle Williamson", "Integration", "New York", "61", "2012/12/02"]
];
// set c to the column number you want to sort
// c=0; will sort the first column
// c=1; will sort the second column ... etc
c=0; // for the example, set c to sort the first column.
array.sort (
function (a, b) {
if (a[c] === b[c]) {
return 0;
} else {
return (a[c] < b[c]) ? -1 : 1;
}
}
);
Example 1:
Printing the array to the console, the array before sorting looks like this:
console.table(array);
Printing the array to the console after sorting, shows it was sorted on column 1.
sorted with c=0;
console.table(array);