How to sort an (associative) array by value?

Possible duplicate:
How to sort associative array by its values ​​in javascript?

So, firstly, I know that technically Javascript does not have associative arrays, but I was not sure how to smooth it out and get the right idea.

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 so that the first pass through it is ROB , then BOB , etc.

I tried,

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

But none of them seem to be doing anything.

Listing the array to the console before and after causes it to exit in the same order.

+6
javascript
Oct 08 '12 at 19:17
source share
4 answers

Arrays can only have numeric indices. You will need to rewrite this as 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 using:

 status.sort(function(a,b) { return a.val - b.val; }); 
+21
Oct 08 '12 at 19:23
source share

At first. It is incorrect to create an array to use as a match. Use Object instead:

 var status = {}; status['BOB'] = 10; 

An array is a class with logic for processing numeric sequential indices.

Now, in answering your answer, the comparisons are not in order, there is no guarantee that it will be iterated, so there is no such thing as “sorting a display”

I suggest you use an array with objects with a key, value:

 var status = []; status.push({ key: 'BOB', value: 10 }); 

Or two arrays:

 var status = { keys: [], values: [] }; status.keys.push('BOB'); status.value.push(10); 

It depends on your needs.

+2
Oct 08 '12 at 19:26
source share

Arrays in javascript are numerically indexed. "Objects" is what you would call an associative array. "Objects" are inherently disordered.

To do this, you need to slightly modify the data structure.

 var arr = []; // Array // push a few objects to the array. arr.push({name: 'BOB', age: 10}); arr.push({name: 'TOM', age: 3}); arr.push({name: 'ROB', age: 22}); arr.push({name: 'JON', age: 7}); var sorted = arr.sort(function(a, b) { return a.age - b.age; }); console.log(sorted); 

enter image description here

+2
Oct 08 '12 at 19:29
source share

You must use a JavaScript object inside the array: jsfidle

  var status = new Array(); status.push({key: 'BOB', value: 10}); status.push({key: 'TOM', value: 3}); status.push({key: 'ROB', value: 22}); status.push({key: 'JON', value: 7}); status.sort(function(a, b){ if(a.value > b.value){ return -1; } else if(a.value < b.value){ return 1; } return 0; }); 
+1
Oct 08 '12 at 19:27
source share



All Articles