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

245
Vistas
Simplifying a nested loop in a javascript function

I have this function in JS

function getMap(objectList) {
  const objectMap = new Map();
  IDS.foreach(id => {
    const attribute = objectList.find(object => object.getId() === id);
    if (attribute) {
      objectMap.set(id, attribute);
    } else {
      objectMap.set(id, null);
    }
}

This is a nested loop because of the find inside the for loop. How could this be simplified? If the nested loop cannot be simplified, can other parts be simplified?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Assuming object IDs are unique, it looks like all you really have to do is call getId on each object beforehand. The conditional operator may be used instead of if/else if you wish.

function getMap(objectList) {
    const objectsById = new Map(
        objectList.map(object => [object.getId(), object])
    );
    const objectMap = new Map();
    for (const id of IDS) {
        objectMap.set(id, objectsById.get(id) || null);
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

You could create an array with null entries for each ID, followed by entries for which you actually have values in objectList, and pass that array to the Map constructor:

function getMap(objectList) {
  return new Map([
    ...IDs.map(id => [id, null]),
    ...objectList.map(object => [object.getId(), object])
  ]);
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

Using native code with a simple callback

const result = (IDS || []).map(function(id, idx, arr) {
    const pos = (objectList || []).findIndex(object => object.getId() === id);
    const output = [];
    output[id] = (pos >= 0 ? objectList[pos] : null);
    return output;
});

Hope this helps... ;D

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