Prevent pushing duplicate object in array in Angular

I have a child component that receives data via @Input() from parent component (array of objects). I map that data and push object in new array for each object from Input data array in ngOnChanges hook. My goal is to prevent duplicates objects being pushed in new array. Every time ngOnChanges fires new objects are being pushed to admins array. I've tried to use some method in if statement but it didn't help. Here is my OnChanges hook:

ngOnChanges() {
  this.adminsGroup.map(a => {
    this.authService.getSpecUser(a.user).subscribe(
      data => {
        data.position = a.permissions;
        this.admins.push(data);
      }
    )
  });
}

So I want to ensure that there is no data already in this.admins array before pushing it. Any help would be appreciated.

Upvotes: 1

Views: 2351

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 710

Checking against a specific property say 'id' in data for uniqueness.

if (!this.admins.some(el => el.id === data.id)) {
  this.admins.push(data);
}

Upvotes: 2

Gustavo Gabriel
Gustavo Gabriel

Reputation: 1296

If data has a unique ID you can just do:

let foundAdmin = this.admins.find(admin => admin.id == data.id);
if (foundAdmin == null)
    this.admins.push(data);

If it doesn't:

let foundAdmin = this.admins.find(admin => JSON.stringify(admin) === JSON.stringify(data));
if (foundAdmin == null)
    this.admins.push(data);

Upvotes: -1

Related Questions