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.

5
  • 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. Commented Oct 8, 2012 at 19:18
  • 2
    Also: Sorting JavaScript Object by property value. Commented Oct 8, 2012 at 19:22
  • Although marked as a duplicate the solution(s) presented below are not mentioned in the duplicate. Commented Oct 8, 2012 at 23:23
  • This 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, 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. Commented Oct 8, 2012 at 23:51
  • Please have a look to my answer stackoverflow.com/a/51116578/1078556 Commented Jun 30, 2018 at 16:27

4 Answers 4

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;
});
Sign up to request clarification or add additional context in comments.

5 Comments

I like this (Array) approach, what would be the proper way to call and sort by val?
I've updated my answer to include sorting by val with an Array of Objects.
Great & Simple solution.
and the same sort for the "Object method"?
@PieroAlberto No, key order cannot be depended on in Objects. Objects are more or less an unordered set of Key-Value pairs. MDN covers this well.
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

1 Comment

How to sort it by name?
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.

Comments

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

1 Comment

This is good for String comparison

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.