Remove an Item from an Array, use Slice & Concat

Tell us what’s happening:

Why code below doesn’t work? The error on test window stated that …
// running test
Dispatching the removeItem action creator should remove items from the state and should NOT mutate state.
// tests completed
… but I use slice() and I don’t mutate the state. Where it could be wrong?

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
      return state.slice(0, action.index + 1).concat(state.slice(action.index + 1));
      break;
    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 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/front-end-libraries/redux/remove-an-item-from-an-array

1 Like

That’s right, just realized I make a mistake on the logic. This code below works:

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
      
      // return [...state.filter((elem, idx) => { 
      //   return idx !== action.index
      // })];
      return state.slice(0, action.index).concat(state.slice(action.index + 1));
      break;
    default:
      return state;
  }
};

const removeItem = (index) => {
  return {
    type: 'REMOVE_ITEM',
    index
  }
}

const store = Redux.createStore(immutableReducer);

Ah, sorry for that. Thanks.