Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 491
silintzir Avatar asked Feb 25 '15 13:02

silintzir


2 Answers

var sortedCollection = _.sortBy(collection, function(item){   return firstArray.indexOf(item.guid) }); 
like image 99
idbehold Avatar answered Sep 24 '22 03:09

idbehold


Here is just a simple add to the accepted answer in case you want to put the unmatched elements at the end of the sortedCollection and not at the beginning:

const last = collection.length;  var sortedCollection = _.sortBy(collection, function(item) {   return firstArray.indexOf(item.guid) !== -1? firstArray.indexOf(item.guid) : last; }); 
like image 41
Alvaro Avatar answered Sep 23 '22 03:09

Alvaro