Retrieving Values with and without Duplicating from JSON Object using Google Apps Script

Gists

This is a sample script for retrieving the values with and without duplicating from JSON object using Google Apps Script. Also this can be used by Javascript.

Sample script

var obj = [
  { key1: "value1a", key2: "value1b" },
  { key1: "value2a", key2: "value2b" },
  { key1: "value5a", key2: "value5b" },
  { key1: "value3a", key2: "value3b" },
  { key1: "value1a", key2: "value1b" },
  { key1: "value4a", key2: "value4b" },
  { key1: "value5a", key2: "value5b" },
  { key1: "value3a", key2: "value3b" }
];

var res = obj.reduce(
  function(obj, e) {
    if (
      obj.withoutDuplicating.some(function(f) {
        return f.key1 === e.key1 && f.key2 === e.key2;
      })
    ) {
      obj.withDuplicating.push(e);
    } else {
      obj.withoutDuplicating.push(e);
    }
    return obj;
  },
  { withoutDuplicating: [], withDuplicating: [] }
);

Logger.log(res);

Result

{
  "withoutDuplicating": [
    {
      "key1": "value1a",
      "key2": "value1b"
    },
    {
      "key1": "value2a",
      "key2": "value2b"
    },
    {
      "key1": "value5a",
      "key2": "value5b"
    },
    {
      "key1": "value3a",
      "key2": "value3b"
    },
    {
      "key1": "value4a",
      "key2": "value4b"
    }
  ],
  "withDuplicating": [
    {
      "key1": "value1a",
      "key2": "value1b"
    },
    {
      "key1": "value5a",
      "key2": "value5b"
    },
    {
      "key1": "value3a",
      "key2": "value3b"
    }
  ]
}

Note

  • As other situation, when f.key1 === e.key1 && f.key2 === e.key2 is modified to f.key1 === e.key1, the duplication of key1 can be retrieved.

Reference

 Share!