tags:

views:

34

answers:

2

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

+2  A: 

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, zero, or less than zero. the first indicates a comes before b, zero means they are equal, the last option means b first.

lincolnk
Thanks, it works.
Noe
A: 

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;
});
Matthew Phipps
That site seems to be talking about reusing the sort callback parameter names within the function. There is no reason not to use `a[1] - b[1]` here.
Daniel Vandersluis
Ah, good point; since the callback has no assignments. Oops.
Matthew Phipps