如何防止数组中出现重复项?

时间:2019-09-24 16:18:50

标签: javascript arrays reactjs filter duplicates

我有两个数组,我想将某些项目从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) => {

                                })
                            }
                        }
                    })
                });

4 个答案:

答案 0 :(得分:3)

您可以使用集合而不是数组。它们具有防止重复输入的内置功能。参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

答案 1 :(得分:3)

我不知道您的User.findByIdAndUpdate$push会做什么,但是如果您只想将第一个数组中第二个数组中的非重复项组合在一起,则仅当标记比较有效时,您可以这样写:

const addWithoutDups = (arr1, arr2, ids = new Set (arr1 .map (x => x .lessonId))) => 
  [
    ...arr1, 
    ...arr2.filter((x) => !ids .has (x .lessonId) && x .obtainedMarks > x .passingMarks)
  ]

const arr1 = [
  {lessonId: 1, more: 'here...'}, 
  {lessonId: 2, more: 'here...'}, 
  {lessonId: 3, more: 'here...'}, 
  {lessonId: 4, more: 'here...'}
]
const arr2 = [
  {lessonId: 2, obtainedMarks: 10, passingMarks: 7},
  {lessonId: 3, obtainedMarks: 5, passingMarks: 12},
  {lessonId: 5, obtainedMarks: 10, passingMarks: 6},
  {lessonId: 7, obtainedMarks: 13, passingMarks: 8},
  {lessonId: 11, obtainedMarks: 10, passingMarks: 15},
]

console .log (
  addWithoutDups (arr1, arr2)
)

请注意,标识23被作为重复项拒绝,标识11不能通过限定,但是标识57已正确添加。 / p>

还要注意,这将返回一个包含数据的新数组;它不会改变原始的。 (我不会参加这种s亵活动!)

答案 2 :(得分:1)

如果项目相同->它们具有相同的引用,请使用Set作为Sokushinbutsu的答案

如果没有,请使用Array.prototype.some()

const arr1Difference = arr1.filter((arr1Item) => {
   const isSomeInArr2 = arr2.some((arr2Item) => {
        return arr1Item.lessonId === arr2Item.lessonId
        // return arr1Item === arr2Item (In the case that items are same -> they have same reference)
   })

   return !isSomeInArr2 
})

const arr2AddToArr1Difference = [...arr2, ...arr1Difference ]

答案 3 :(得分:1)

您创建一个Set的arr1 lessonId,然后使用数组过滤器从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
  );