Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
-4
rated 0 times [  3] [ 7]  / answers: 1 / hits: 34798  / 12 Years ago, mon, october 8, 2012, 12:00:00

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.


More From » javascript

 Answers
68

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

[#82684] Sunday, October 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ryans

Total Points: 514
Total Questions: 92
Total Answers: 121

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
;