Akbar Basha Akbar Basha - 3 months ago 17
Javascript Question

how to remove redundant array objects

I need to remove all the duplicate elements, for example:

var arr = [
{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1,pointIndex:1},
{'seriesIndex':0,pointIndex:0},
{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1}
]


How to remove redundant (duplicate) array objects from an array?

My expected output is:

arr = [
{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1,pointIndex:1},
{'seriesIndex':0,pointIndex:0},
{'seriesIndex':1}
]


How to achieve this?

Answer

In vanilla Javascript, I'd suggest to keep track of the encountered composite keys while iterating on the list in a .reduce() method. The test on prv.key[key] is O(1) (hashtable lookup), so this algorithm is O(n).

var arr = [
  {seriesIndex:1, pointIndex:0},
  {seriesIndex:1, pointIndex:1},
  {seriesIndex:0, pointIndex:0},
  {seriesIndex:1, pointIndex:0},
  {seriesIndex:1}
];

arr = arr.reduce(function(prv, cur) {
  var key = cur.seriesIndex + '/' + cur.pointIndex;

  if(!prv.key[key]) {
    prv.key[key] = true;
    prv.res.push(cur);
  }
  return prv;
}, {key: {}, res: []}).res;

console.log(arr);