Remove an Item from an Array, use Slice & Concat

Remove an Item from an Array, use Slice & Concat
0

#1

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


#2

Your code does not mutate state, but it also does not return an array with the element specified by the index removed.


#3

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);

#4

That is good you solved. It really is not necessary to post your full working solution, so I have blurred it to prevent spoiling the solution for others still working on this challenge.


#5

Ah, sorry for that. Thanks.