用对象筛选数组



我有以下数组:


arr = [
[
{
id: 1,
name: 'name 1',
pushname: 'name 1'
}
],
[
{
id: 2,
name: 'name 2',
pushname: 'name 2'
}
],
[
{
id: 1,
name: 'name 1',
pushname: 'name 1'
}
]
]
/*return:
[
[ { id: 1, name: 'name 1', pushname: 'name 1' } ],
[ { id: 2, name: 'name 2', pushname: 'name 2' } ],
[ { id: 1, name: 'name 1', pushname: 'name 1' } ]
]
*/

如何删除重复的信息?

我想返回:

/*
[
[ { id: 1, name: 'name 1', pushname: 'name 1' } ],
[ { id: 2, name: 'name 2', pushname: 'name 2' } ]
]
*/

我相信我会使用过滤器,但我尝试了几种方法,都没有找到解决方案。有人知道怎么帮我吗?

注意:我是初学者!对不起,如果问题重复,我将排除它!

因此,根据您的情况,这可以帮助

arr = [
[
{
id: 1,
name: "name 1",
pushname: "name 1",
},
],
[
{
id: 2,
name: "name 2",
pushname: "name 2",
},
],
[
{
id: 1,
name: "name 1",
pushname: "name 1",
},
],
];
// Create a reference Array
let visitedID = [];
// Perform filter operation
arr = arr.filter((element) => {
//   check if the value is present (repetetion)
if (visitedID.includes(element[0].id)) {
return false;
} else {
// Push the data to the array and return
visitedID.push(element[0].id);
return true;
}
});
console.log(arr);

:为了使这个条件有效,你必须确保元素是唯一的,有ID,我们基本上是创建一个ID的数组,并根据ID过滤它们,以及它们是否在visitedID数组中可用。

我也很困惑,为什么你要创建一个Array[Array[Object]]代替,我们可以使用Array[Objects]和过滤器部分也很容易。如果您希望更改表单,您可以使用评论中提到的答案。

编辑:你可以从这个问题中采用这种简写方法。这应该有帮助从javascript的对象数组中删除重复的值

所以…重要的事先做。

在JS中比较数组有点棘手,如果你想了解更多,我会参考这个问题:如何在JavaScript中比较数组?

我对这个问题的解决方案如下:

function removeDuplicates(source) {
const newArray = [];   //Create a new array where the results are stored as String
for(let element of source){ //Iterate through the provided array (source)
const stringified = JSON.stringify(element) //Convert the current element into a JSON String
if(!newArray.includes(stringified)) //Check if the Element is alread added into the new List, if not add it
newArray.push(stringified) //Add it here
}
return newArray.map(JSON.parse); //Convert the String-Array into an Object-Array and return
}

这可能不是最优雅的解决方案,但你有一个特殊的情况,你有一个数组,其中包含数组,这使事情变得复杂。

希望我能帮到你:)如果你有后续问题,请随时提问!

最新更新