Search code examples
javascriptarray-algorithms

Comparing Two Lists, Updating if Different


I have a program written in JavaScript that runs CRUD operations depending if the items in one lists are different from the other. Basically comparing two lists, main list and mirror list. The constraints are:

  • If an object is in the main list, but not the mirror list, add it to the mirror list

  • If an object is in the mirror list, but not in the main list, delete it from the mirror list

What would be an efficient way to perform this check? Currently, I am iterating through two for loops which seems inefficient.

for (const mainId of Object.keys(mainItems)) {
      if (!Object.keys(mirrorItems).includes(mainId)) {
        await createEvent(mainItems[mainId])
      }
}

for (const mirrorId of Object.keys(mirrorItems)) {
      if (!Object.keys(mainItems).includes(mirrorId)) {
        await deleteEvent(mirrorItems[mirrorId])
      }
}


Solution

  • From your codes it looks like you are comparing keys of objects, not just arbitrary arrays. Therefore you would want mirrorItems to have the same keys as mainItems but not the same values (otherwise that would just be a copy).

    Using a Set which performs lookups in O(1) promotes your solution from a solution running in O(n²) to one running in O(n).

    Additionally you need reduce().

    const obj = {
      matching: "A matching property but a different value",
      missing: "A property which is missing in mirror, should be added",
    };
    
    const mirror = {
      matching:
        "A matching property but a different value, to see that there is not just a copy created",
      additional: "An additional property which should be deleted",
    };
    
    const set = new Set(Object.keys(mirror));
    const correctMirror = Object.keys(obj).reduce(
      (mirrored, cur) => (
        set.has(cur)
          ? // if the property exist on the obj, we can keep the current value
            (mirrored[cur] = mirror[cur])
          : // if the property does not exist on obj, we need to get the value from obj and assign it to the mirror
            (mirrored[cur] = obj[cur]),
            // return mirrored for next iteration or result
        mirrored
      ),
      {}
    );
    console.log(correctMirror);
    .as-console-wrapper { max-height: 100% !important; top: 0; }