3

I am trying to add and delete an obect from an array, I have been able to figure out the add object part, but the deletion is not working. I have used filter() but it did nothing. Now I am using splice, it works but it deletes the first element, instead of the selected item. below is a sample code, and I have shown only the functions for better clarity.

        handleDelete(item) {

          this.setState(({ list}) => {
            const newList = [...list];
            newList.splice(item.key, 1);
            console.log('deleted', newList);
            return { list: newList };
          });
        }


        handleAdd() {
          const { firstname, lastname, email, phone} = this.state;
          const ID = uuid();
          const newItemObject = {
              key: ID,
              firstname: firstname,
              lastname: lastname,
              email: email,
              phone: phone,
              image: null,
          };

          this.setState(prevState => ({
            list: [...prevState.list, newItemObject]
          }));
        }

I would like to

1 Answer 1

5

The item's key and index in the array are probably not the same. If the item is in the array, you can use Array.indexOf() to find it's index, and splice it out:

handleDelete(item) {
  this.setState(({ list }) => {
    const newList = [...list];
    const index = newList.indexOf(item);
    newList.splice(index, 1);

    return {
      list: newList
    };
  });
}

Or if you want to use Array.filter(), check if the key of of current element (o) is different from that of item:

handleDelete(item) {
  this.setState(({ list }) => ({
    list: list.filter(o => o.key !== item.key)
  }))
}
Sign up to request clarification or add additional context in comments.

4 Comments

many thanks, both methods worked. but which is better to use?
The filter method is shorter and concise, and doesn't create another redundant array (the removed items from slice). I would use filter.
have another question, but i dont know if its proper to ask another question under a different question thread
The comments are used to discussion the specific question/answer. Create a new question.

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.