javascript 如何从打字稿数组中删除重复项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47840061/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:37:12  来源:igfitidea点击:

How to remove duplicates from a typescript array?

javascriptarrays

提问by user2753523

Could you let me know how do I remove duplicates from an Array in type script.

你能告诉我如何从类型脚本中的数组中删除重复项吗?

My array will look something like

我的阵列看起来像

a = [{a: 1, b: 2}, {a: 1, b: 2}, {c: 3, d: 4}]

I am looking to get

我正在寻找

a = [{a: 1, b: 2}, {c: 3, d: 4}]

I used Set data strucure like below

我使用了如下设置数据结构

a = Array.from(new Set(a))

but still no use. Please let me know how to remove duplicates from an array using single statement?

但还是没有用。请让我知道如何使用单个语句从数组中删除重复项?

回答by Ciro Spaciari

Is not in a single statement but is short.

不是在一个单一的声明中,而是简短的。

var a = [{a: 1, b: 2}, {a: 1, b: 2}, {c: 3, d: 4}];
a = a.filter((value, index, array) => 
     !array.filter((v, i) => JSON.stringify(value) == JSON.stringify(v) && i < index).length);

console.log(a);
你的问题是这样的:

Delete duplicated elements in array of objects Javascript

删除对象数组中的重复元素Javascript

But like in the comment will fails for:

但就像在评论中会失败:

var a = [{a: 1, b: 2}, {b: 2, a: 1}]; 

You need a custom compare for your case:

您需要为您的案例进行自定义比较:

function isEqual(a, b){
  for(var i in a)
       if(a[i] != b[i])
          return false;
  for(var i in b)
       if(b[i] != a[i])
          return false;
  return true;
}

var a = [{a: 1, b: 2}, {b: 2, a: 1}, {c: 3, d: 4}];
a = a.filter((value, index, array) => 
     !array.filter((v, i) => isEqual(value, v) && i < index).length);

console.log(a);

You can compare ids or somenthing like this to identify equal object in this sample i just compare the properties.

您可以比较 ids 或类似的东西来识别此示例中的相同对象,我只是比较属性。

Like @Juan Mendes said in comment:

就像@Juan Mendes 在评论中所说:

The reason your code doesn't filter elements is because two similar objects are still considered different objects because they point to different objects. You need to write your own code that uses a custom comparator.

您的代码不过滤元素的原因是两个相似的对象仍然被视为不同的对象,因为它们指向不同的对象。您需要编写自己的使用自定义比较器的代码。