0

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')
  }
})
Peter B
  • 22,460
  • 5
  • 32
  • 69
ANUBIS
  • 666
  • 1
  • 9
  • 20
  • 1
    what is the ideal way of comparison you have in your mind then? check all fields (case sensitive/insensitive)? if that is the case, why not simply add a check? – Ji_in_coding Aug 22 '18 at 15:49

2 Answers2

2

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?

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
1

You can use some to check if that object already exists, if not, add it:

if (!Instructor.some(i => i.ID == instance.ID)) {
    Instructor.push(instance);
}
tymeJV
  • 103,943
  • 14
  • 161
  • 157