Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/clojure/3.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
javascript使用reduce展平数组并删除重复项_Javascript_Arrays_Ecmascript 6 - Fatal编程技术网

javascript使用reduce展平数组并删除重复项

javascript使用reduce展平数组并删除重复项,javascript,arrays,ecmascript-6,Javascript,Arrays,Ecmascript 6,我尝试使用reduce和Set一步展平阵列并删除重复项,但阵列已展平,但重复项仍保留 相关的答案涉及到从阵列中删除重复项,但我希望在一个步骤中展平并删除重复项,因此我建议这可能不是一个重复的问题 const wells=[ [{ id:1, 名字:'好的一个' }, { id:2, 名字:“两口井” }, { id:3, 名字:“三号井” }, ], [{ id:2, 名字:“两口井” }, { id:3, 名字:“三号井” }, { id:4, 名字:“四号井” }, ], ]; const

我尝试使用
reduce
Set
一步展平阵列并删除重复项,但阵列已展平,但重复项仍保留

相关的答案涉及到从阵列中删除重复项,但我希望在一个步骤中展平并删除重复项,因此我建议这可能不是一个重复的问题

const wells=[
[{
id:1,
名字:'好的一个'
},
{
id:2,
名字:“两口井”
},
{
id:3,
名字:“三号井”
},
],
[{
id:2,
名字:“两口井”
},
{
id:3,
名字:“三号井”
},
{
id:4,
名字:“四号井”
},
],
];
const uniqueflattedWells=wells.reduce(
(a,b)=>Array.from(新集合(a.concat(b)),[],
);

console.log(UniqueFlattedWells)
对象只有在它们是完全相同的引用时才相等。解决此问题的一种方法是使用
JSON.stringify
来比较对象,但请注意,这不是最快的方法

const wells=[
[{
id:1,
名字:'好的一个'
},
{
id:2,
名字:“两口井”
},
{
id:3,
名字:“三号井”
},
],
[{
id:2,
名字:“两口井”
},
{
id:3,
名字:“三号井”
},
{
id:4,
名字:“四号井”
},
],
];
const uniqueflattedwells=((set)=>wells.reduce((a,b)=>a.concat(b),[])。filter(obj=>{
const str=JSON.stringify(obj);
return!set.has(str)&set.add(str);
})
)(新一套);
console.log(UniqueFlattedWells)
您可以使用和如果ID确定项目是否重复:

const wells=[[{“id”:1,“name”:“well one”},{“id”:2,“name”:“well two”},{“id”:3,“name”:“well two”},{“id”:2,“name”:“well two”},{“id”:3,“name”:“well two”},{“id”:4,“name”:“well two”}];
const uniqueflattedWells=wells.reduce(
(a,b)=>a.concat(b.filter(o=>a.every(x=>x.id!==o.id)),
[],
);

console.log(UniqueFlattedWells)
对象彼此之间没有
=
,因此集合不会重复消除我编辑了问题,使其重新打开,因为建议的答案谈到删除重复项,但我希望一步完成重复项的展平和删除。所以希望它能重新开放