Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent duplicate items in array?

I have two arrays, i want to push some items from arr1 to arr2 preventing duplicates because i've already added some items to arr2 that are also in arr1. i am doing this in 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) => {

                                })
                            }
                        }
                    })
                });
like image 973
Adnan Babai Avatar asked Jul 13 '26 19:07

Adnan Babai


1 Answers

You can use a set instead of an array. They have the built in feature of preventing duplicate entries. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

like image 194
Sokushinbutsu Avatar answered Jul 15 '26 08:07

Sokushinbutsu