Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Created May 30, 2019 05:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/16ba2c77cdc8caa6a02958c9a4006e8a to your computer and use it in GitHub Desktop.
Save tanaikech/16ba2c77cdc8caa6a02958c9a4006e8a to your computer and use it in GitHub Desktop.
Retrieving Values with and without Duplicating from JSON Object using Google Apps Script

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment