0

Possible Duplicate:
Simple function to sort an array of objects

While writing the script, there was a problem with sorting an array. I have an array of objects:

[{gold: false, range: 1601}, {gold: true, range: 13}, {gold: false, range: 375}, {gold: true, range: 601}

But it should look like this:

[{gold: true, range: 13}, {gold: true, range: 601}, {gold:false, range: 375}, {gold: false, range: 1601}]

I want to get an array in which the keys are sorted by increasing range. But if there gold key value is true, then they are the first.

Community
  • 1
  • 1

2 Answers2

11

Use something like this:

yourArray.sort(function(a, b){
    return a["gold"] == b["gold"] ? a["range"] - b["range"] : a["gold"] ? -1 : 1;
});

Or even this:

yourArray.sort(function(a, b){
    return  b["gold"] - a["gold"] || a["range"] - b["range"];
});

The second approach is really cool actually)) You can just use this pattern for any number of fields in your object, just order them by their importance. If some field should be sorted as ascending - than a["..."] - b["...], if as descending - than b["..."] - a["..."]

SergeyS
  • 3,515
  • 18
  • 27
3

Try

var arr = [{gold: false, range: 1601}, {gold: true, range: 13}, {gold: false, range: 375}, {gold: true, range: 601}], 
    sorter = function(a, b) {
      if(a.gold && !b.gold) {return -1;}
      if(!a.gold && b.gold) {return 1;}
      return a.range - b.range;
    };

arr.sort(sorter);
Yury Tarabanko
  • 44,270
  • 9
  • 84
  • 98