Why is my code not working? "Remove an Item from an Array"

Tell us what’s happening:
I checked out Slice()

And state.slice(action.index, action.index + 1) should return the index and not mutate the state.
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((action.index) , (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 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36.

Challenge: Remove an Item from an Array

Link to the challenge:

Finish writing the reducer so a new state array is returned with the item at the specific index removed.

I don’t think your code does this. You’re returning the removed item.

1 Like

@JeremyLT is right what you want to do return is an array that has all the items of the old array, but the item you wish to remove. You may find this of use: Spread syntax (...) - JavaScript | MDN

1 Like

You need to make very little modifications to get your code to pass, and so you know if you spread an array as such ...[1,2,3] what that basically does is create 1,2,3, and only a few things can accept a list of items, such as an array

1 Like

This is my solution


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
      let remove = state.slice(action.index, action.index + 1)
    let newState = [...state];
    function not(value) {
      return value != remove;
    }

      return newState.filter(not);
    default:
      return state;
  }
};

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

const store = Redux.createStore(immutableReducer);

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.