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
        }
    );
}
4
  • 2
    accountsToAdd = accountsToAdd.filter(e => e.id !== id); Commented Mar 15, 2018 at 14:19
  • Possible duplicate of Javascript: How to filter object array based on attributes? Commented Mar 15, 2018 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. Commented Mar 15, 2018 at 14:25
  • @SandraWillford the approved answer of the duplicate I provided is using filter Commented Mar 15, 2018 at 14:27

1 Answer 1

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.

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

2 Comments

thanks, ben's comment was pretty much the same approach and so this works like a charm!
@SandraWillford yeah, haven't seen the comment, as I wrote this example for u.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.