Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an (associative) array by value? [duplicate]

Tags:

javascript

Possible Duplicate:
How to sort an associative array by its values in Javascript?

So first off I know technically Javascript doesn't have associative arrays, but I wasn't sure how to title it and get the right idea across.

So here is the code I have,

var status = new Array();
status['BOB'] = 10
status['TOM'] = 3
status['ROB'] = 22
status['JON'] = 7

And I want to sort it by value such that when I loop through it later on ROB comes first, then BOB, etc.

I've tried,

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

But none of them seem to actually DO anything.

Printing the array out to the console before and after result in it coming out in the same order.

like image 600
PopeJohnPaulII Avatar asked Oct 08 '12 19:10

PopeJohnPaulII


1 Answers

Arrays can only have numeric indexes. You'd need to rewrite this as either an Object, or an Array of Objects.

var status = new Object();
status['BOB'] = 10
status['TOM'] = 3
status['ROB'] = 22
status['JON'] = 7

or

var status = new Array();
status.push({name: 'BOB', val: 10});
status.push({name: 'TOM', val: 3});
status.push({name: 'ROB', val: 22});
status.push({name: 'JON', val: 7});

If you like the status.push method, you can sort it with:

status.sort(function(a,b) {
    return a.val - b.val;
});
like image 191
saml Avatar answered Oct 26 '22 09:10

saml