Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a 2D array by the second value

Tags:

javascript

I have an array and I want to sort by the number field not the name.

var showIt = [
  ["nuCycleDate",19561100],
  ["ndCycleDate",19460700],
  ["neCycleDate",0],
  ["nlCycleDate",0]
];

Thanks

like image 861
Noe Avatar asked Aug 19 '10 18:08

Noe


People also ask

How do you sort a 2D array?

To sort all elements of a 2D array by row-wise. As in the above rewrite program, the sort() method is used to iterate each element of a 2D array and sort the array row-wise. Finally, the print method displays all the elements of the 2D array.

How do you sort a 2D array by value 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.

How do you sort a 2D array based on the first element?

To column-wise sort a 2D Array in Java, call the “Arrays. sort()” method with a “Comparator interface”. A Comparator interface defines a “compare()” method that accepts two parameters and then compares them with each other. If the passed parameters are equal, it returns zero.


2 Answers

You can provide sort with a comparison function.

showIt.sort(function(a, b) {
    return a[1] - b[1];
});

a and b are items from your array. sort expects a return value that is greater than zero, equal to zero, or less than zero. The first indicates a comes before b, zero means they are equal, and the last option means b first.

like image 99
lincolnk Avatar answered Oct 09 '22 07:10

lincolnk


This site advises against using the arguments without assigning to temporary variables. Try this instead:

showIt.sort(function(a, b) {
    var x = a[1];
    var y = b[1];
    return x - y;
});
like image 21
Vanessa Phipps Avatar answered Oct 09 '22 09:10

Vanessa Phipps