Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 483
Alex Avatar asked Apr 19 '13 03:04

Alex


People also ask

How do I sort an array by a column?

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.

How do you sort a 2D array?

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.

How do you sort a 2D array by a column in Python?

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.


4 Answers

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;
    }
}
like image 166
jahroy Avatar answered Oct 13 '22 06:10

jahroy


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]
});
like image 43
Pramod Vemulapalli Avatar answered Oct 13 '22 05:10

Pramod Vemulapalli


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.

like image 61
PSR Avatar answered Oct 13 '22 05:10

PSR


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)
like image 15
Dinesh Rajan Avatar answered Oct 13 '22 04:10

Dinesh Rajan