11

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.

Community
  • 1
  • 1
PopeJohnPaulII
  • 765
  • 2
  • 7
  • 10
  • 4
    That is the wrong usage of JS arrays. Only use numeric keys with arrays. `.sort` does not do anything because strictly speaking your array does not have any elements. You have to use objects in this case. I recommend to read [MDN - Working with Objects](https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects). – Felix Kling Oct 08 '12 at 19:18
  • 2
    Also: [Sorting JavaScript Object by property value](http://stackoverflow.com/questions/1069666/sorting-javascript-object-by-property-value). – Felix Kling Oct 08 '12 at 19:22
  • Although marked as a duplicate the solution(s) presented below are not mentioned in the duplicate. – PopeJohnPaulII Oct 08 '12 at 23:23
  • [This](http://stackoverflow.com/a/1069840/218196) is pretty much the same as suggested in all the answers below. It just uses an array of arrays instead of an array of objects. It's a subtle difference which does not change the big picture of the solution. Same goes for [the accepted answer in the duplicate question](http://stackoverflow.com/a/5200010/218196), it just provides a way of programmatically converting an object into an array of arrays... which is more useful than a hardcoded example only. All the information here is provided in the other questions as well. – Felix Kling Oct 08 '12 at 23:51
  • Please have a look to my answer https://stackoverflow.com/a/51116578/1078556 – danicotra Jun 30 '18 at 16:27

4 Answers4

25

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;
});
saml
  • 6,702
  • 1
  • 34
  • 30
3

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

So to do this you would need to change your data structure a bit.

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

Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
2

First - It's incorrect to create a Array to use it as a Mapping. Instead use Object:

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

The Array is a class with logic to handle numeric-sequential indexes.

Now answering your response, Mappings have no order, there is no guarantee about the order it will iterate so there is no such thing as "sorting a mapping"

I sugest you to use a array with objects with 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's up to your needs.

A. Matías Quezada
  • 1,886
  • 17
  • 34
1

You should use JavaScript Object inside 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;
    });
Anoop
  • 23,044
  • 10
  • 62
  • 76