0

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?

8
  • JSON.stringify() usually works to produce a comparable version of a data object. if your keys are not in a consistent order, its going to be more complicated. much more. Commented Jun 23, 2015 at 22:06
  • 2
    You probably want to check for deep equality. Various libraries implement such a function. Basically recursively iterate over the data structures and compare. Commented Jun 23, 2015 at 22:07
  • @FelixKling Could you name some libs which can do that? Commented Jun 23, 2015 at 22:19
  • 1
    lodash.com, underscorejs.org, google.com/search?q=deep+equal+javascript Commented Jun 23, 2015 at 22:20
  • @FelixKling underscore.js is the first think out of my mind, but I can not figure out how to use its _.uniq function with array with objects, could you give a simple example? Commented Jun 23, 2015 at 22:22

1 Answer 1

2

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>")

Sign up to request clarification or add additional context in comments.

2 Comments

Why should the OP "try" this? Are you not confident that it will work?
@FelixKling Excuse my audacity to "try" because of my language, although after I always edit my answers for a explanation.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.