-1

I am trying to remove duplicate form list of arrays that are present in an object and object looks like bellow , for example i am only using two array but there are many in actual array that i am looking at

{
    "NAME":[
        "LORD",
        "OF",
        "RINGS",
        "LORD"
    ],
    "ADRESS":[
        "INDIA",
        "INDIA",
        "TEXAS",
        "SRILANKA"
    ]
}

Expected output :

{
    "NAME":[
        "LORD",
        "OF",
        "RINGS"
    ],
    "ADRESS":[
        "INDIA",
        "TEXAS",
        "SRILANKA"
    ]
}

Currently I am able to pull out a single array from object and am able to remove duplicates using "SET" bellow is my code

console.log("without duplicates", [... new Set(r.NAME)]);

Since it is an object i am sure i cant loop on this. How can i achieve the expected output , Thanks

Divakar
  • 41
  • 5

4 Answers4

2

You can iterate over the object keys and then use Set to remove duplicates like so:

    function removeDuplicates(obj): any {
        for (const key of Object.keys(obj)) {
            obj[key] = [...new Set(obj[key])];
        }
        return obj;
    }
Alex Kolarski
  • 3,255
  • 1
  • 25
  • 35
0
    const obj = {
      NAME: ["LORD", "OF", "RINGS", "LORD"],
      ADDRESS: ["INDIA", "INDIA", "TEXAS", "SRILANKA"]
    };
//get array of keys
const keys = Object.keys(obj);

//then map to transform the object array
const sets = keys.map(key => new Set(obj[key]));

//set back to array
keys.forEach((key, i) => {
  obj[key] = [...sets[i]];
});

console.log(obj);
Anil
  • 986
  • 10
  • 21
0

We can use Set to remove the duplicate

let data = {
   "NAME":[
      "LORD",
      "OF",
      "RINGS",
      "LORD"
   ],
   "ADRESS":[
      "INDIA",
      "INDIA",
      "TEXAS",
      "SRILANKA"
   ]
}

Object.keys(data).forEach(k => {
  data[k] = [...new Set(data[k])]
})

console.log(data)
flyingfox
  • 13,414
  • 3
  • 24
  • 39
0

How about this way?

const originDatas = {
  "NAME":[
    "LORD",
    "OF",
    "RINGS",
    "LORD",
  ],
  "ADRESS":[
    "INDIA",
    "INIDA",
    "TEXAS",
    "SRILANKA",
  ],
};

const setDatas = {};

Object.keys(originDatas).map((key) => {
  setDatas[key] = [...new Set(originDatas[key])];
});

console.log(setDatas);
ChanHyeok-Im
  • 541
  • 3
  • 11