Kuan
Kuan

Reputation: 11389

remove duplicated object in array

All:

I wonder if there is a way to quickly remove duplicated object from array.

The object inside the array is positon info, like:

var coordinates = [
{x:1, y:2},
{x:1, y:3},
{x:1, y:2},
{x:1, y:2}
]

The final output should be only 2 points:

[
{x:1, y:2},
{x:1, y:3},
]

The only way I can think out is:

var uniquetable = {}
coordinates.forEach(function(d, i){
    uniquetable[d.x+"_"+d.y] = d;
});
coordinates  = [];
for(var k in uniquetable) {
    coordinates.push( uniquetable[k] );    
}

But when the position is multi-dimension(like adding extra object-type attributes, I have no idea how to do like this), for example:

var coordinates = [
{x:1, y:2, style:{color:'red'}},
{x:1, y:3, style:{color:'blue'}},
{x:1, y:2, style:{color:'green'}},
{x:1, y:2, style:{color:'red'}}
]

I wonder how can I quickly remove duplicated objects?

Upvotes: 0

Views: 107

Answers (1)

You can use filter. You check with uniqueFn if the string exists in the temp var. Then you keep the element if it is true

var coordinates = [
  {x:1, y:2, style: {color:'red'}},
  {x:1, y:3, style: {color:'blue'}},
  {x:1, y:2, style: {color:'green'}},
  {x:1, y:2, style: {color:'red'}}
];

var uniqueFn = function(val){
  return [val.x, val.y, val.style.color].join()
}, temp = [];

coordinates = coordinates.filter(function(val){
  return temp.indexOf(uniqueFn(val)) == -1 ? temp.push(uniqueFn(val)) : false
});

document.write("<pre>" + JSON.stringify(coordinates, 0, 3) + "</pre>")

Upvotes: 2

Related Questions