Redux - Remove an Item from an Array

Tell us what’s happening:
Following is my code using splice it is not passing, but why? I checked the hint section and it is using slice. Isn’t my code doing the same as the slice code?
I didn’t understand the hint code as it is using slice twice

      return [
        ...state.slice(0, action.index),
        ...state.slice(action.index + 1, state.length)
      ];

Why? It doesn’t say in question from where we have to start.

Your code so far

const immutableReducer = (state = [0,1,2,3,4,5], action) => {
  switch(action.type) {
    case 'REMOVE_ITEM':
      // Don't mutate state here or the tests will fail
      const copiedArr = [...state].splice(action.index, 1);
      console.log(copiedArr, "copied arr");
      return copiedArr
    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 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36

Challenge: Redux - Remove an Item from an Array

Link to the challenge:

1 Like

Your code may be doing what slice is doing but it is also doing one thing extra - it is mutating the array. slice does not change the old array, it creates a new one and returns that. splice creates a whole new array and returns that. [Edit: I should have said that splice mutates the old array and returns and array of removed elements.]

Remember - in Redux, every time we mutate state, Dan Abramov strangles a puppy.

I have a hard time remembering what the different prototype methods do. Get in the habit of googling “mdn array slice” and “mdn array splice” or whatever.

I am confused because slice and splice both return a new array from your definition.

:rofl:

Sorry, typo. splice mutates the old array and returns an array of removed items.

READ THE DOCS - Seriously, google “MDN array splice” and read - that is one of the most important skills a developer has - finding and reading the docs.