Remove an Item from an Array

Remove an Item from an Array
0.0 0

#1

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


#2

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

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)

#4

Hi @aditya2000

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


#5

Thank you for this answer


#6

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