m0_37285193 于 2017.01.11 14:58 提问

javascript中数组里对象怎么去重
`````` var arr1 = [{x:513.4261838440111,y:174},
{x:270.3404255319149,y:174},
{x:513.4261838440111,y:174},
{x:520.5167237931058,y:369.80798782499784},
{x:520.5167237931058,y:369.80798782499784},
{x:241.57929926401988,y:381.9650668601638},
{x:270.3404255319149,y:174},
{x:241.5792992640199,y:381.9650668601638}
]
``````

8个回答

showbo      2017.01.11 15:21
``````
var arr1 = [
{ x: 513.4261838440111, y: 174 },
{ x: 270.3404255319149, y: 174 },
{ x: 513.4261838440111, y: 174 },
{ x: 520.5167237931058, y: 369.80798782499784 },
{ x: 520.5167237931058, y: 369.80798782499784 },
{ x: 241.57929926401988, y: 381.9650668601638 },
{ x: 270.3404255319149, y: 174 },
{ x: 241.5792992640199, y: 381.9650668601638 }
]
var kv = {}
for (var i = 0; i < arr1.length;) {
if (kv[arr1[i].x + ',' + arr1[i].y]) {
arr1.splice(i, 1);
}
else {
kv[arr1[i].x + ',' + arr1[i].y] = true;
i++;
}
}
console.log(arr1)
``````
li_wenbiao   2017.01.11 14:57

m0_37285193 可以详细写么。大哥，最好代码上手

qq_35235940   2017.01.11 15:07
m0_37285193 纯数组去重与数组中对象去重不一样

m0_37285193   2017.01.11 15:20

`````` for (var i = 0;i<arr1.length;i++) {
for (var j =1;j<arr1.length-1;j++) {
if(arr1[i].x == arr1[j].x){
arr1.splice(j,1)
}
}
}
console.log(arr1)
``````
li_wenbiao 你这段代码有问题的，j++处有bug，可以参考楼下showbo的处理方式，这种方式同时减少了一层for循环的嵌套！

u010715243   2017.01.11 15:22

li_wenbiao   2017.01.11 15:30

var kv = [];

\$.map(arr1, function (obj) {
if (obj.x != kv[obj.x] && obj.y != kv[obj.y]) {
kv[obj.x] = obj.y;
}
});

``````
``````
dcxy0      2017.01.11 16:11

http://es6.ruanyifeng.com/#docs/set-map

u014386892   2017.01.12 11:11
``````  var kv = {};
var arr = arr1.filter(function(obj) {
if (!kv[obj.x + ',' + obj.y]) {
kv[obj.x + ',' + obj.y] = true;
return obj;
}
})
console.log(arr);
``````