Lodash sort collection based on external array

silintzir picture silintzir · Feb 25, 2015 · Viewed 11.3k times · Source

I have an array with keys like so:

['asdf12','39342aa','12399','129asg',...] 

and a collection which has these keys in each object like so:

[{guid: '39342aa', name: 'John'},{guid: '129asg', name: 'Mary'}, ... ]

Is there a fast way to sort the collection based on the order of keys in the first array?

Answer

idbehold picture idbehold · Feb 25, 2015
var sortedCollection = _.sortBy(collection, function(item){
  return firstArray.indexOf(item.guid)
});