0

I have this code:

const user = {courses: [
    {id: '1A', code: '111'},
    {id: '2B', code: '222'}
]}

const courseID = '1A'
const course = {id: '1A', code: '111'}

for(var i=0; i<user['courses'].length; i++) {
    var course_ID = user['courses'][i]['id']
    if (courseID !== course_ID) {
        user['courses'].push(course)
        break
    }
}
console.log(user)

After running the code, I expect this result:

{
  courses: [
    { id: '1A', code: '111' },
    { id: '2B', code: '222' }
  ]
}

But it shows this result:

{
  courses: [
    { id: '1A', code: '111' },
    { id: '2B', code: '222' },
    { id: '1A', code: '111' } 
  ]
}

How can I solve this problem?

5
  • Step 1: i=0 course_ID="1A" courseID !== course_ID. Step 2: i=1 course_ID="2B" courseID === course_ID => user['courses'].push(course) Commented Aug 20, 2020 at 14:58
  • you can filter array first, then add objects to it Commented Aug 20, 2020 at 14:58
  • You could use a set to control the ids you are entering into the array as sets do not allow duplicate values. Commented Aug 20, 2020 at 14:59
  • 1
    Does this answer your question? Preventing array from adding duplicate element Commented Aug 20, 2020 at 15:02
  • 1
    @PrathameshMore You should not assume you know who downvoted, nor should you tell people how to use their votes. Commented Aug 20, 2020 at 15:04

2 Answers 2

3

You can use different methods for checking objects inside array

For example you can use find to determine there is an object inside your array

// finding element inside array `courses` with id === courseID
const arrayItem = user.courses.find(item => item.id === courseID)

// if element not found
if(!arrayItem) {
  user.courses.push(course)
}
Sign up to request clarification or add additional context in comments.

Comments

0

This happens because inside the loop you are doing your ID check. So for the first run it will not add and not break out of the loop, because the condition is not met. But on the second run ID of second course will not match and you will push to the array. You have to improve your logic a bit in order to get desired result. Try using find instead to check if the item you are going to add already exists in the array

const user = {
  courses: [
      {id: '1A', code: '111'},
      {id: '2B', code: '222'}
  ]
}

const courseID = '1A'
const course = {id: '1A', code: '111'};
const courses = user.courses;

const courseExists = courses.find(course => course.id == courseID);

if (!courseExists) {
  courses.push(course);
};

console.log(user)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.