Why can't you use array.prototype.filter in Redux reducer

Tell us what’s happening:

Per MDN array.prototype.filter creates a new array (and doesn’t mutate the original). However when I implement the following code I can’t pass the test as I don’t meet the criteria:

Dispatching the removeItem action creator should remove items from the state and should NOT mutate state.

In my mind I am not mutating the original state, I am creating a new array with filter. Am I wrong?

Even when I replace state.filter() with [...state].filter() I still fail the test for the same reason.

Any help is appreciated :slight_smile:

Your code so far


const immutableReducer = (state = [0,1,2,3,4,5], action) => {
switch(action.type) {
  case 'REMOVE_ITEM':
      return state.filter(item => item != action.index);
  default:
    return state;
}
};

const removeItem = (index) => {
return {
  type: 'REMOVE_ITEM',
  index
}
}
const store = Redux.createStore(immutableReducer);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 Edg/88.0.705.50.

Challenge: Remove an Item from an Array

Link to the challenge:

Hello there,

The test text is misleading; it is complaining, because your reducer does not return the correct values.

Think about what you are comparing here:

state.filter(item => item != action.index);

And, take another look at the docs: Array.prototype.filter() - JavaScript | MDN (mozilla.org)

Click, if you are still stuck:

Currently, you are comparing the item itself with the index passed as the payload in the action. What should happen is, if the item's index matches the index passed, it should be removed.

Hope this helps

1 Like

Thank you for the help! I had read the question wrong: I thought I was supposed to filter based on the number itself… not the index position. Your explanation helped me understand that

But I am glad to know that I was not mutating the state itself.