Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

207
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda