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

243
Views
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 answers
Answer question

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 Report

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 Report

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