0

I have two arrays, both of objects.

Charities (unordered):

[{
    "_id": "5527c2b29a4c7ebe2953129d",
    "name": "Lorem ipsum",
    "number": 1,
    "metric": "Lorem ipsum",
    "metricConversion": 6,
    "logo": "http://api.fake.net/example.png",
    "country": "Albania",
    "twitter": "exampletwitter",
    "facebook": "examplefb"
}, ...]

Promotions:

[{
    "type": 1,
    "charity": "5527c2b29a4c7ebe2953129d",
    "start": Sun May 10 2015 14:11:32 GMT+0100 (BST),
    "end": Thu Jul 02 2009 00:00:00 GMT+0100 (BST),
    "priority": 10
}, ...]

The promotions array is ordered by the priority (greatest first).

What I am trying to do is order the charities array by the promotions array, so the charity with the highest value for priority is put first, etc (with the connection being _id to charity).

I can think of several easy ways to do this, however the ones that come to mind are very inefficient. Any suggestions?

1 Answer 1

2

Create a map with the charity id as key and index (or priority) as value:

var map = {};
for (var i = 0; i < promotions.length; i++) {
  map[promotions[i].charity] = i;
}

Now you can sort the charities and use the map to determine their ordering:

charities.sort(function(a, b){
  return map[a._id] - map[b._id];
});
Sign up to request clarification or add additional context in comments.

2 Comments

map[a._id] - map[b._id] returns NaN if there isn't a promotion for one of the charities (presumably as map[..] is undefined)
@BenedictLewis: Yes, that's right. I assumed that there were promotions for all the charities. If there aren't, then you need to decide how you want to sort the charities that doesn't have a charity.

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.