如何从数组中删除重复的点?

时间:2018-05-23 07:36:36

标签: javascript

我有这一系列的观点:

0:Point {X: 181708.79357001217, Y: 659243.26713151, rotate: ƒ, move: ƒ, resize: ƒ, …}
1:Point {X: 182534.29357001217, Y: 657010.1837981766, rotate: ƒ, move: ƒ, resize: ƒ, …}
2:Point {X: 186545.37690334552, Y: 660957.76713151, rotate: ƒ, move: ƒ, resize: ƒ, …}
3:Point {X: 181708.79357001217, Y: 659243.26713151,rotate: ƒ, move: ƒ, resize: ƒ, …}

我需要删除具有相同坐标的点。

例如,索引0和3的点具有相同的坐标。所以在我删除之后,期望得到这个数组:

0:Point {X: 181708.79357001217, Y: 659243.26713151, rotate: ƒ, move: ƒ, resize: ƒ, …}
1:Point {X: 182534.29357001217, Y: 657010.1837981766, rotate: ƒ, move: ƒ, resize: ƒ, …}
2:Point {X: 186545.37690334552, Y: 660957.76713151, rotate: ƒ, move: ƒ, resize: ƒ, …}

所以我的问题是如何才能使用javascript删除aary中的重复点?

1 个答案:

答案 0 :(得分:1)

let array = [
  {X: 181708.79357001217, Y: 659243.26713151},
  {X: 182534.29357001217, Y: 657010.1837981766},
  {X: 186545.37690334552, Y: 660957.76713151},
  {X: 181708.79357001217, Y: 659243.26713151}
]

let answer = [];

array.forEach(arr=> {
    if(!answer.some(an => JSON.stringify(an) === JSON.stringify(arr))){
    answer.push(arr);
  }
});

以上代码将循环遍历数组,检查answer的唯一性,如果唯一,则将其推入answer