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?
var sortedCollection = _.sortBy(collection, function(item){ return firstArray.indexOf(item.guid) });
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; });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With