Home > other >  How to check for duplicate data sets in JSON payload using JavaScript?
How to check for duplicate data sets in JSON payload using JavaScript?

Time:10-01

I would like to find duplicate data sets from below payload using combination of 'NAME', 'ID'. If a duplicate data set exist, I need to return NAME, ID of duplicated data set.

{
"Test": "1",
"value": [
    {
        "NAME": "ABCD",
        "ID": "1234",
        "ACTIVE": "true"
    },
    {
        "NAME": "EFGH",
        "ID": "5678",
        "ACTIVE": "true"
    },
    {
        "NAME": "ABCD",
        "ID": "1234",
        "ACTIVE": "true"
    },
    {
        "NAME": "EFGH",
        "ID": "5678",
        "ACTIVE": "true"
    },
    {
        "NAME": "IJKL",
        "ID": "91011",
        "ACTIVE": "true"
    }
   ]
}

Expected output:

["ABCD:1234","EFGH:5678"]

CodePudding user response:

this questuon was answered multiple times on SO. You create array from the json and compare the elements of the array.

How to remove all duplicates from an array of objects?

CodePudding user response:

Try this. You can improve this further by performance wise, if you work around a bit.

 var data = {
 "Test": "1",
 "value": [
    {
        "NAME": "ABCD",
        "ID": "1234",
        "ACTIVE": "true"
    },
    {
        "NAME": "EFGH",
        "ID": "5678",
        "ACTIVE": "true"
    },
    {
        "NAME": "ABCD",
        "ID": "1234",
        "ACTIVE": "true"
    },
    {
        "NAME": "EFGH",
        "ID": "5678",
        "ACTIVE": "true"
    },
    {
        "NAME": "IJKL",
        "ID": "91011",
        "ACTIVE": "true"
    }
   ]
 };
 var objArray = data.value;
 var duplicates = []; // duplicates will be stored here.
 for(var i=0, iLen = objArray.length; i<iLen;i  ){
    var obj = objArray[i];
        var filtered = objArray.filter(function(arrVal) {
        return arrVal.NAME === obj.NAME && arrVal.ID === obj.ID ;
    });
    filtered.forEach(function(item){
    var dup = item.NAME   ":"   item.ID;
    if(duplicates.indexOf(dup) < 0)
        duplicates.push(dup);
    });
 }
  • Related