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
NumPy arrays can be sorted by a single column, row, or by multiple columns or rows using the argsort() function. The argsort function returns a list of indices that will sort the values in an array in ascending value.
Example #2 Example for 2D array sorting in Java to sort all elements of a 2D array by column-wise. As in the above rewrite program, the sort() method is used to iterate each element of a 2D array and sort the array column-wise. Finally, the print method displays all the elements of the 2D array.
Sorting 2D Numpy Array by column at index 1 Select the column at index 1 from 2D numpy array i.e. It returns the values at 2nd column i.e. column at index position 1 i.e. Now get the array of indices that sort this column i.e. It returns the index positions that can sort the above column i.e.
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((a, b) => a[0] - b[0]);
//WITH SECOND COLUMN
arr = arr.sort((a, b) => 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With