Search code examples
javascriptarrayscollectionsunderscore.jslodash

Lodash sort collection based on external array


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?


Solution

  • var sortedCollection = _.sortBy(collection, function(item){
      return firstArray.indexOf(item.guid)
    });