1

I have two arrays like these:

objects = [Obj1, Obj2, Obj3];
scores  = [10,200,15];

with objects[i] corresponding to its score in scores[i].

I need to sort the objects array in a descending order, depending on their relative scores.

Any idea how to do that efficiently in jQuery/javascript ? Thank you for your help !

3
  • 4
    It would probably be better to join them together as a single object and then sort them. Commented Jan 3, 2015 at 15:54
  • Do you also want scores sorted? Commented Jan 3, 2015 at 16:06
  • Wouldn't it be easier to keep the scores as a property of the object it belongs to ? Commented Jan 3, 2015 at 16:08

1 Answer 1

2

As @Rory McCrossan suggests, probably the best approach is to join the values together and then separate them afterward if desired:

// produces [{score: 10,  value: Obj1}, 
//           {score: 200, value: Obj2},
//           {score: 15,  value: Obj3}]
var joined = objects.map(function (el, i) {
    return { score: scores[i], value: el };
});

// rearranges joined array to:
//          [{score: 200, value: Obj2},
//           {score: 15,  value: Obj3},
//           {score: 10,  value: Obj1}]
joined.sort(function (l, r) { return r.score - l.score; });

// produces [Obj2, Obj3, Obj1]
var sorted = joined.map(function (el) { return el.value; });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.