Home > Net >  Simplifying a nested loop in a javascript function
Simplifying a nested loop in a javascript function

Time:06-28

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?

CodePudding user response:

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);
    }
}

CodePudding user response:

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])
  ]);
}

CodePudding user response:

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

  • Related