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.

1
  • explain your problem in details Commented Dec 29, 2012 at 12:27

2 Answers 2

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["..."]

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.