我有两个数组,我想将某些项目从arr1推送到arr2,以防止重复,因为我已经将一些项目也添加到了arr1中。我在React JS中这样做
arr1.forEach(q1 => {
arr2.forEach(q2 => {
if (q1.lessonId !== q2.lessonId) {
if (q2.obtainedMarks >= q2.passingMarks) {
User.findByIdAndUpdate(req.body.userId, { $push: { arr1: { $each:
[q2._id] } } }, (err, doc) => {
})
}
}
})
});
最佳答案
您创建arr1 lessonId的Set,然后使用数组过滤器从arr1中已经存在的arr2中过滤掉所有内容,然后再次过滤以仅获取通过的项目:
//get all lessonId for arr1 in a Set
const arr1Ids = new Set(arr1.map(x=>x.lessonId));
//get items of arr2 that are not already in arr1
const passingArr2NotInArr1 = arr2
.filter(
//take out everything that is already in arr1
item => !arr1Ids.has(item.lessonId)
)
.filter(
//only when it passed
item => item.obtainedMarks >= item.passingMarks
);
关于javascript - 如何防止数组中出现重复项?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58084473/