Remove an Item from an Array Redux :)

Remove an Item from an Array Redux :)
0

#1

Tell us what’s happening:

Meant to return the new state (array) with a item gone. I have done this using concat and filter. But it is not accepting it…have I missread the question by any chance?

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.concat().filter(x => x != 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; rv:64.0) Gecko/20100101 Firefox/64.0.

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


#2

OK, first of all, you don’t need filter.

Think of it this way. You need to split the array into two pieces - one before the index and one after. You will have two arrays you can assign them into variables if you want, but you can also do it all in one line. You don’t need to check the index against the array or find it - they’re giving it to you. How do you split an array? slice is good for that because it also creates a new array that it returns - meaning that you won’t mutate state (every time you mutate state, a puppy dies). Then you have to join those two together and return them. The ES5 way to join them is with concat and the ES6 way uses the spread operator. Either will work.


#3

Aaaah hell no! It should have rang alarm bells when it said index…Here I was removing a number from the list not the actual index…face palm. Thanks @kevinSmith


#4

Trust me, those “oh my god I feel like an idiot” moments are just part of being a programmer. Any day that I have fewer than 10 of those is a good day.