0

In the following function I push and object to the accountsToDelete array, I need to then remove the matching object from the accountsToAdd array. I am guessing I would have to use a combination of IndexOf, Filter, Reduce but I am still a little rough in understanding how to accomplish this. This is the current function:

accountDelete(id, name) {
    const accountsToAdd = this.userForm.value.accountsToAdd;
    const accountsToDelete = this.userForm.value.accountsToDelete;
    this.userForm.value.accountsToDelete.push(
        {
            id: id,
            name: name
        }
    );
}
Sandra Willford
  • 3,459
  • 11
  • 49
  • 96
  • 2
    `accountsToAdd = accountsToAdd.filter(e => e.id !== id);` – baao Mar 15 '18 at 14:19
  • Possible duplicate of [Javascript: How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes) – ben Mar 15 '18 at 14:22
  • @ben it may be a duplicate, but I am glad I asked it as @baao solution is a simple one line of code and I was specifically asking how to accomplish this using the `filter()` method. – Sandra Willford Mar 15 '18 at 14:25
  • @SandraWillford the approved answer of the duplicate I provided is using `filter` – ben Mar 15 '18 at 14:27

1 Answers1

1

You can simply use the filter function. By this you can say, that in the accountToAdd all entries should be filtered, which id fits the to deleted account.

An example:

// Initialize both lists.
let accountsToAdd = []
let accountsToDelete = []

// Preparation by adding a account to the first list.
const account = { id: 1, name: 'Max' }
accountsToAdd.push(account)

// Mark account to be removed.
accountsToDelete.push(account)
accountsToAdd = accountsToAdd.filter(acc => acc.id !== account.id)

// Verify result.
console.log(accountsToAdd)
console.log(accountsToDelete)


Note:
Your both lists are defined as constant. By this you can't use the reassignment.

weilbith
  • 564
  • 4
  • 20