Retrieving Difference Between 2 Arrays using Google Apps Script

Gists

This is a sample script for retrieving the difference between 2 arrays, which are the old values and the new values, using Google Apps Script. In my environment, I sometimes have the situation that it is required to retrieve the difference between 2 arrays. So I prepared this as a sample script. I think that this can be also used at Javascript and Node.js. If this was also useful for your situation, I’m glad.

Sample script

In this sample script, the difference of the values of oldValues and newValues is retrieved as an object.

const getDiffFrom2Arrays = (oldValues, newValues) => {
  const inputObjects = [
    { name: "oldValues", value: oldValues },
    { name: "newValues", value: newValues },
  ];
  const object = inputObjects.reduce(
    (o1, { name, value }) =>
      Object.assign(o1, {
        [name]: value.reduce(
          (o2, f) => Object.assign(o2, { [f]: o2[f] ? o2[f] + 1 : 1 }),
          {}
        ),
      }),
    {}
  );
  const diff1 = Object.entries(object.newValues).reduce(
    (o, [k, v]) => {
      if (object.oldValues[k]) {
        const d = v - object.oldValues[k];
        o.changed.push({ [k]: ((d < 0 || d == 0 ? "" : "+") + d).toString() });
      } else {
        o.addedNewValues.push({ [k]: v });
      }
      return o;
    },
    { addedNewValues: [], changed: [] }
  );
  const diff2 = Object.entries(object.oldValues).reduce(
    (o, [k, v]) => {
      if (!object.newValues[k]) o.removed.push({ [k]: v });
      return o;
    },
    { removed: [] }
  );
  return Object.assign(diff1, diff2);
};

const oldValues = ["a1", "b1", "b1", "c1", "d1", "e1"];
const newValues = ["a1", "b1", "d1", "a1", "d1", "f1", "g1", "a1", "g1"];
const res = getDiffFrom2Arrays(oldValues, newValues);
console.log(JSON.stringify(res)); // {"addedNewValues":[{"f1":1},{"g1":2}],"changed":[{"a1":"+2"},{"b1":"-1"},{"d1":"+1"}],"removed":[{"c1":1},{"e1":1}]}

Result

When above script is run, the following result is returned.

{
  "addedNewValues": [{ "f1": 1 }, { "g1": 2 }],
  "changed": [{ "a1": "+2" }, { "b1": "-1" }, { "d1": "+1" }],
  "removed": [{ "c1": 1 }, { "e1": 1 }]
}

Testing

jsfiddle.net

 Share!