JS Built-ins
redux-legacyreducerintermediate

Array State β€” Removing Items

πŸ“– Usage Example
function reducer(state = [], action) {
  switch (action.type) {
    case 'REMOVE_ITEM':
      return state.filter(item => item.id !== action.payload)
    default: return state
  }
}
reducer([{id:1},{id:2}], {type:'REMOVE_ITEM',payload:1}) // β†’ [{id:2}]

filter() creates a new array excluding the item with the matching id, leaving state immutable.

Array State β€” Removing Items

To remove an item from an array state without mutating, use Array.prototype.filter():

case 'REMOVE_ITEM': return state.filter(item => item.id !== action.payload)

filter() always returns a new array containing only the items that pass the test.

Challenge: Implement reducer(state = [], action) that handles 'REMOVE_ITEM'. The state is an array of objects with an id field; action.payload is the id to remove.

πŸ’‘ Hints (2)
  • β€’ `state.filter(item => item.id !== action.payload)` keeps all items except the one to remove.
  • β€’ `filter()` returns a new array β€” it never modifies the original.