1

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?

1
  • 1
    no there aren't Commented Dec 5, 2020 at 2:50

3 Answers 3

1

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)

Sign up to request clarification or add additional context in comments.

2 Comments

I was thinking about this problem for a few hours now. Yeah you are right. I'll go this way.
@AfshinM.Khiabani please mark as answered if that solved your problem I've added another option for you if you wan't you could test it and add it to the array prototype
1

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);
  }
}

Comments

0

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);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.