Search code examples
javascriptarraysobjectjavascript-objects

How to compare each element in array to one single value?


I have an array with multiple objects inside. It's structured like that:

const Instructor = [
  { ID: '141',
    InstructorNameAR: 'test',
    InstructorNameEN: 'Mohamed Ahmed',
    InstructorBriefAR: 'phd in chemistry',
    InstructorBriefEN: 'phd in chemistry' },
  { ID: '140',
    InstructorNameAR: 'test',
    InstructorNameEN: 'Mahmoud Ahmed',
    InstructorBriefAR: 'phd in chemistry',
    InstructorBriefEN: 'phd in chemistry' },
]

I wanted to add other objects but filtered of duplicates based on their ID values.

Example of objects i want to add :-

  const InstructorInstance = {
    ID: 'ID',
    InstructorNameAR:   'NAMEAR',
    InstructorNameEN:   'NAMEEN',
    InstructorBriefAR:  'BRIEFAR',
    InstructorBriefEN : 'BRIEFEN'
  }

I used this method to filter by ID. But it didn't work as it compares only a single value of the array to the value i provided. which means it might be a duplicated object but still gets added because it did not check if it exists in each array element

Instructor.forEach(instance =>{
  if(instance.ID !== InstructorInstance.ID){
    Instructor.push(InstructorInstance);
  }else{
    console.log('Duplicate')
  }
})

Solution

  • You have to loop the whole array first before deciding whether there is a duplicate or not. You can use forEach for that but every or some seem like the perfect fit for this kind of job:

    const test = Instructor.every(instance => instance.ID !== InstructorInstance.ID);
    if(test) {
        Instructor.push(InstructorInstance);
    }
    

    Which means if every object in Instructor has a different ID than InstructorInstance, then push InstructorInstance into Instructor.

    Note: You can put the test directly inside if without having to store it in a variable test:

    if(Instructor.every(instance => instance.ID !== InstructorInstance.ID)) {
        Instructor.push(InstructorInstance);
    }
    

    But that doesn't look, does it?