Skip to content Skip to sidebar Skip to footer

Comparing Arrays Of Objects And Remove Duplicate

I have an array containing arrays of objects which I need to compare. I've looked through multiple similar threads, but I couldn't find a proper one that compares multiple arrays o

Solution 1:

you can achieve so by using function.As below. Not sure about best optimum way of doing so.

var testArray = [  
  [  
    {  
      "id": "65",
      "name": "Some object name",
      "value": 90
    },
    {  
      "id": "89",
      "name": "Second Item",
      "value": 20
    }
  ],
  [  
    {  
      "id": "89",
      "name": "Second Item",
      "value": 20
    },
    {  
      "id": "65",
      "name": "Some object name",
      "value": 90
    }
  ],
  [  
    {  
      "id": "14",
      "name": "Third one",
      "value": 10
    }
  ]
]

functionremoveDuplicatesFromArray(arr){

 var obj={};
 var uniqueArr=[];
 for(var i=0;i<arr.length;i++){ 
    if(!obj.hasOwnProperty(arr[i])){
        obj[arr[i]] = arr[i];
        uniqueArr.push(arr[i]);
    }
 }

return uniqueArr;

}
var newArr = removeDuplicatesFromArray(testArray);
console.log(newArr);

Solution 2:

const data = [  
  [  
    {  
      "id": "65",
      "name": "Some object name",
      "value": 90
    },
    {  
      "id": "89",
      "name": "Second Item",
      "value": 20
    }
  ],
  [  
    {  
      "id": "89",
      "name": "Second Item",
      "value": 20
    },
    {  
      "id": "65",
      "name": "Some object name",
      "value": 90
    }
  ],
  [  
    {  
      "id": "14",
      "name": "Third one",
      "value": 10
    }
  ]
];

const temp = {};
const result = [];

data.forEach(itemArr => {
  const items = itemArr.filter(item => {
    const isUnique = temp[`${item.id}-${item.name}-${item.value}`] === undefined;
    
    temp[`${item.id}-${item.name}-${item.value}`] = true;
    return isUnique;
  });
  if (items.length !== 0)
    result.push(items);
});

console.log(result);

Post a Comment for "Comparing Arrays Of Objects And Remove Duplicate"