Sort a two-dimensional array by the second value

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

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

thank

+3
source share
2 answers

You can provide sorta comparison function.

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

aand b- these are elements from your array. sort expects a return value that is greater than zero, zero, or less than zero. the first indicates that it aprecedes b, zero means that they are equal, the last option means bfirst.

+17
source

This site advises against using arguments without reference to temporary variables. Try instead:

showIt.sort(function(a, b) {
    var x = a[1];
    var y = b[1];
    return x - y;
});
+1
source

Source: https://habr.com/ru/post/1760612/


All Articles