Noe
Noe

Reputation: 105

Sort a 2D array by the second value

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

Upvotes: 6

Views: 24865

Answers (3)

Arya More
Arya More

Reputation: 1

        var temp;
        var newarr= [showIt[0][1],showIt[1][1],showIt[2][1],showIt[3][1]];
        //document.write(newarr);
        for(i=0;i<showIt.length;i++){
            for(j=i+1;j<=showIt.length;j++){
            if(newarr[i] > newarr[j]){
                temp = showIt[i];
                showIt[i]=showIt[j];
                showIt[j]=temp;
            }
        }
        }
        document.write(showIt);

Upvotes: -1

lincolnk
lincolnk

Reputation: 11238

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.

Upvotes: 24

Vanessa Phipps
Vanessa Phipps

Reputation: 2390

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;
});

Upvotes: 1

Related Questions