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

206
Views
Array.find with Array.map in Javascript

I have two arrays, in the first one I store some user data. In the second, I store the basic data about the users.

const usersData = [{ userId: 1, age: 18 }];
const users = [{id: 1, name: 'Alex'}];

I wrote some simple code below:

const result = usersData.map(userData => {
    return {
        ...userData,
        userName: users.find(user => user.id === userData.userId).name
    }
})

After that, I get the result:

const result = [{ userId: 1, age: 18, name: "Alex" }];

The question is: how can you write this solution in a simpler way? Maybe should use the library "Lodash"?


Sorry, my English is not so good.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

For larger datasets, it's better to use a different data structure to increase the performance of the lookup and reduce the runtime.

const usersData = [{ userId: 1, age: 18 }];
const users = [{id: 1, name: 'Alex'}];
const usersById = Object.fromEntries(users.map(user => ([user.id, user])));

const result = usersData.map(userData => {
    return {
        ...userData,
        userName: usersById[userData.userId]?.name
    }
})

console.log(result);

about 4 years ago · Juan Pablo Isaza Report

0

There is nothing simpler than this way, but you can optimise it so that you don't have to use find for every key. For that you can use Map here.

Note: If are trying to use any library, then under the hood they might be using the same method

const usersData = [{ userId: 1, age: 18 }];
const users = [{id: 1, name: 'Alex'}];

const usersDict = new Map();  // dictionary for users
users.forEach(o => usersDict.set(o.id, o));

const result = usersData.map(user => ({ ...user, username: usersDict.get(user.userId)?.name}))

console.log(result);

about 4 years ago · Juan Pablo Isaza 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!