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.
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;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With