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

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

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

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

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 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