Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

var sortedCollection = _.sortBy(collection, function(item){
  return firstArray.indexOf(item.guid)
});
over 4 years ago · Santiago Trujillo Report

0

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;
});
over 4 years ago · Santiago Trujillo Report

0

Input:

var data1 = ['129asg', '39342aa'];
var data2 = [{
    guid: '39342aa',
    name: 'John'
}, {
    guid: '129asg',
    name: 'Mary'
}];
  1. First create an index object, with _.reduce, like this

    var indexObject = _.reduce(data2, function(result, currentObject) {
        result[currentObject.guid] = currentObject;
        return result;
    }, {});
    
  2. And then map the items of the first array with the objects from the indexObject, like this

    console.log(_.map(data1, function(currentGUID) {
        return indexObject[currentGUID]
    }));
    

Output

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

Note: This method will be very efficient if you want to sort so many objects, because it will reduce the linear look-up in the second array which would make the entire logic run in O(M * N) time complexity.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!