-9

I'm trying to sort a multi-dimensionsal array that looks like the following:

 var test_array = { "214": { "id": "214", "name": "Mike Smith", "salary": 50000 }, 
"336": { "id": "336", "name": "John Doe", "salary": 60000 }, 
"134": { "id": "134", "name": "Jane Doe", "salary": 100000 }, 
"914": { "id": "914", "name": "Bob White", "salary": 25000 } };

I'd like to sort descending by the salary field and jQuery functions are acceptable in the solution.

cgdeveloper
  • 53
  • 1
  • 1
  • 6

1 Answers1

2

You can't sort your array, because in fact it's an object instead of an array.

And JS objects are unordered collections of name/value pairs.

If you want order, use arrays instead of objects, e.g.

var test_array = [
    { "id": "214", "name": "Mike Smith", "salary": 50000 }, 
    { "id": "336", "name": "John Doe", "salary": 60000 }, 
    { "id": "134", "name": "Jane Doe", "salary": 100000 }, 
    { "id": "914", "name": "Bob White", "salary": 25000 }
];
test_array.sort(function(a,b){
    if(a.salary < b.salary) return -1;
    if(a.salary > b.salary) return 1;
    return 0;
});
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 2
    @Benjamin Gruenbaum: OP doesn't have an array. +1 – zerkms Oct 14 '13 at 23:50
  • @Benjamin Gruenbaum: I don't have any doubts. Which makes this question just *incomplete*, **NOT** *incorrect*. – zerkms Oct 14 '13 at 23:53
  • @zerkms It's not incomplete. OP got the terminology wrong. It's perfectly clear what he wants to accomplish. He wants his id/name/salary objects based on the salary. Which btw Oriol just edited into this answer. I've removed my downvote. – Benjamin Gruenbaum Oct 14 '13 at 23:54