-1

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?

dakab
  • 5,379
  • 9
  • 43
  • 67
Akbar Basha
  • 1,168
  • 1
  • 16
  • 38
  • 5
    Possible duplicate of [Remove Duplicates from JavaScript Array](http://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array) contains one of the best answers I've seen on SO yet in all honesty (second answer down) – N.J.Dawson Aug 15 '16 at 11:43

3 Answers3

2

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);
Arnauld
  • 5,847
  • 2
  • 15
  • 32
1

I use library, which has rich API - lodash

With lodash it looks like :

_.uniqWith(arr, _.isEqual)

It is simple and short

Link to library https://lodash.com/

Sabik
  • 1,599
  • 1
  • 11
  • 10
0

By an invention of Object.prototype.compare() you may do like this

Object.prototype.compare = function(o){
  var ok = Object.keys(this);
  return typeof o === "object" && ok.length === Object.keys(o).length ? ok.every(k => this[k] === o[k]) : false;
};

var arr = [{'seriesIndex':1,pointIndex:0},
           {'seriesIndex':1,pointIndex:1},
           {'seriesIndex':0,pointIndex:0},
           {'seriesIndex':1,pointIndex:0},
           {'seriesIndex':1}
          ],
 result = arr.reduce((res,obj) => res.length === 0 ? res.concat(obj)
                                                   : !!res.find(o => obj.compare(o)) ? res
                                                                                     : res.concat(obj),[]);
console.log(JSON.stringify(result,null,2));
Redu
  • 25,060
  • 6
  • 56
  • 76