Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda