Remove an Item from an Array

Please help me with this code


const immutableReducer = (state = [0,1,2,3,4,5], action) => {
  switch(action.type) {
    case 'REMOVE_ITEM':
      let arr = [...state];
      return arr.splice(action.index, 1)
    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 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.

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

Hi @aditya2000

The problem is that you’re returning the result of calling .splice, which returns the removed element from the array, see here.

What you want to do is return arr after calling .splice

3 Likes

The best choice is splice but.
You can use indexOf. It returns the index of the passed input.
Example:

let arr = [1, 2, 3]
arr[arr.indexOf(1)] = null
arr.filter(e => e !== null)
1 Like

Hi @aditya2000

Use the return [..state.slice(0, action.index), ...state.slice(action.index + 1)] in your reducer.

4 Likes

Thank you for this answer

Thanks a lot to all of you guys. It worked :+1:

Please I’d like to know how this line works… I don’t understand it… thanks… P.S Private message would be much appreciated. Thanks again.