Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 角度-使用集合从阵列中删除重复对象_Arrays_Typescript - Fatal编程技术网

Arrays 角度-使用集合从阵列中删除重复对象

Arrays 角度-使用集合从阵列中删除重复对象,arrays,typescript,Arrays,Typescript,我需要从阵列中删除所有重复的对象。我知道我可以通过使用filter或reduce来实现这一点,但我想改用set,因为(如果它能工作的话)它应该是最短和最干净的选项 原始数组 [{type: "A", label: "A", department: "C"}, {type: "B", label: "B", department: "C"}, {type: "B", label: "B", department: "C"}] 预期输出: [{type: "A", label: "A", depa

我需要从阵列中删除所有重复的对象。我知道我可以通过使用filter或reduce来实现这一点,但我想改用set,因为(如果它能工作的话)它应该是最短和最干净的选项

原始数组

[{type: "A", label: "A", department: "C"},
{type: "B", label: "B", department: "C"},
{type: "B", label: "B", department: "C"}]
预期输出:

[{type: "A", label: "A", department: "C"},
{type: "B", label: "B", department: "C"}]
distinctArray = new Set(origionalArray);
我试过:

[{type: "A", label: "A", department: "C"},
{type: "B", label: "B", department: "C"}]
distinctArray = new Set(origionalArray);
但它返回原始数组。所以我猜它是通过引用来比较对象的。在java中,我将重写equals方法。但就我在网上所能找到的而言,这在TS中是做不到的


你知道我该怎么做吗?感谢您的帮助和时间。

您可以使用此选项从TS中的阵列中删除重复项

const expected = new Set();
const unique = arr.filter(item => !expected.has(JSON.stringify(item)) ? expected.add(JSON.stringify(item)) : false);

您可以在此处找到答案:我尝试了此操作,但它给出了以下错误:“”TS2568:类型“Set”不是数组类型。使用编译器选项“--downlevelIteration”允许迭代器的迭代。“”将“downlevelIteration”:true添加到我的tsconfig不会解决问题。所以我尝试使用Array.from(新集合(origionalArray)。然后错误消失,但我仍然得到OriginalArray,而不是简化的数组。好的,前面的代码仅适用于字符串。我已经更新了对象级检查的答案。arr是您的原始数组,正在进行筛选以删除重复项。谢谢!工作非常完美。我接受了正确的awnser:)很高兴它对您有所帮助。快乐编码:)