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

127
Views
Sort array of object by another array of object

I have two arrays of objects with the same length.

one= 
[
    { id: 3, name: 'a'}, 
    { id: 5, name: 'b'},
    { id: 4, name: 'c'}
];

two= 
[
    { id: 7, name: 'b'}, 
    { id: 6, name: 'c'},
    { id: 2, name: 'a'}
];

I want to sort array 'two' by name property that depends on array 'one'.

My solution is

const tempArray = [];
one.forEach((x) => {
   tempArray.push(two.find(item => item.name === x.name));

But is there a way to do this without creating tempArray?

I mean a one line solution?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You could use map function:

const tempArray = one.map(x => two.find(item => item.name === x.name));

Alternatively, if you are not striving for brevity:

const nameToPosMap = Object.fromEntries(one.map((x, idx) => [x.name, idx]));
two.sort((i1, i2) => nameToPosMap[i1.name] - nameToPosMap[i2.name])

This may be faster as it avoids repeated find calls.

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!