randal
randal

Reputation: 1362

Why does this.state.items.filter removes an item from an array

I know how to remove an item from an array within react, but i do not understand the logic behind why this works.

removeItem(id) => {
   items:[...this.state.items.filter(item => item.id !== id)]
}

All i understand is that if item.id !== id remove the item. But how does this work though ? Why does it remove an item from an array.

Upvotes: 0

Views: 39

Answers (1)

Harsh Makadia
Harsh Makadia

Reputation: 3443

Here is the explanation, the following operations are performed

  1. Filter the array based on some conditions

Consider the following example

// Defining array
const items = [{"id" : 1},{"id" : 2}, {"id" : 3} ]

//Eliminating id 2
const filteredArray = items.filter(item => item.id !== 2)

console.log(filteredArray)

In the above example what filter does is, it returns an array excluding whatever is mentioned in the condition in Our case it's item.id !== id so Object having Id 2 is skipped.

Once that is done, items now hold the updated array of object.

Upvotes: 1

Related Questions