Afshin Mobayen Khiabani
Afshin Mobayen Khiabani

Reputation: 1269

Remove an item inside of an array which is inside of another array in angular?

I have the following Structure:

export class Contact {
    id: number = 0;
    firstname: string = '';
    lastname: string = '';
    phones: Phone[] = [];
    emails: Email[] = [];
}

export class Email {
    id: number = 0;
    emailType: string = '';
    address: string = '';
}

export class Phone {
    id: number = 0;
    phoneType: string = '';
    number: string = '';
}

Now in a component I have an array of Contact named contacts and a phone object. I want to remove that phone object which is in a phones array of a contact which is inside of a contacts array. Is there a simple way like filter or something that can do this easily without going through all contacts with a loop?

Upvotes: 1

Views: 81

Answers (3)

Afshin Mobayen Khiabani
Afshin Mobayen Khiabani

Reputation: 1269

I finally found a way by using filter:

let x = this.contacts.filter(x => x.phones.some(y => y.number == phone.number))[0];
x.phones = x.phones.filter(x => x.id != phone.id);

Or by id:

let x = this.contacts.filter(x => x.phones.some(y => y.id == phone.id))[0];
x.phones = x.phones.filter(x => x.id != phone.id);

Upvotes: 0

meriton
meriton

Reputation: 70564

While you have to use a loop, that needn't be onerous:

for (const contact of contacts) {
    contact.phones = contact.phones.filter(p => p != phone);
}

If you need to modify the existing array rather than creating a new one, you can do:

for (const contact of contacts) {
  remove(phone, contact.phones);
}

where

function remove<T>(item: T, array: T[]) {
  const index = array.indexOf(item);
  if (index > -1) {
    array.splice(index, 1);
  }
}

Upvotes: 1

JSmith
JSmith

Reputation: 4808

I can't think of another way of doing that and also there is 99.9% chances a function like filter would go through a loop

removePhone(contacts, phone){
  for (let i = 0; i < contacts.length; i++){
    const currentPhones = contacts[i].phones;
    for (let j = 0; j < currentPhones.length ; j++)
      if (currentPhones[j] === phone)
        return (currentPhones.splice(j, 1));
  }
}

or based on this post;

you could do something like

function filterAndRemove(array, func) {
  for ( var counter = 0; counter < array.length; counter++) {
    for (let i = array[counter].phones.length - 1; i >= 0 ; i--)  
      if (func(array[counter].phones[i], i, array[counter].phones)) {
        array[counter].phones.splice(i, 1);
    }
  }
}

(not tested)

Upvotes: 1

Related Questions