TodoList Video Quesiton

Hello Kirupa,

I don’t understand your deletedItem(key) function for your TodoList video. Can you explain more?

In the example:

var filteredItems = this.state.items.filter(function (item) {
            return (item.key !== key)

I don’t understand (item.key !==key) here. How the key would be not equal?

Hi @Yi_Li - welcome to the forums :slight_smile:

This is a great question. What this line is doing is going through all of the items in our todo list as specified by this.state.items. We want our filteredItems to retain all of the items in our list except for the one item we remove (which is key).

By checking for item.key !== key, we are letting our filter method know which item to let through and which item to ignore.

To describe differently, it’s like a strainer that lets everything through except for one very particular item, and particular item is the one we want to remove.

Does this help clarify this line of code?


1 Like

I think the person is thinking that in item.key, item refers to the item being deleted. Maybe this will help, or just make things more confusing :stuck_out_tongue_winking_eye:

The reason item.key can not equal key is because key comes from the prop called key on the item that was selected and item.key is the current item being filtered from the list of items.

Each item in the list of items has a unique key that was defined in addItem

  var newItem = {
      text: this._inputElement.value,

When the item is rendered we add a key prop to that items html.
return <li key={item.key}>{item.text}</li>

When deleteItem is called it is passed the key of the item that was selected.

Then it uses the filter to go through the list of todo items creating a new list but excluding the item whos key matches the one passed to deleteItem. The filter function pass’s each todo in the list this.state.items to the function. The todo passed is called item because thats the argument used function (item), so here item refers to the item from the list passed to the function and not the item that was clicked on.

deleteItem(key) {
  var filteredItems = this.state.items.filter(function (item) {
    return (item.key !== key);

And then the state is updated with the new list of items.

    items: filteredItems
1 Like