Cant figure out this one

Tell us what’s happening:

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
default:
return state;
}
};

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

const store = Redux.createStore(immutableReducer);

Your code so far


const immutableReducer = (state = [0,1,2,3,4,5], action) => {
switch(action.type) {
  case 'REMOVE_ITEM':
    const newState = state.filter( val => val !== action.index );
   
    return newState;
  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; CrOS x86_64 13099.72.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.94 Safari/537.36.

Challenge: Remove an Item from an Array

Link to the challenge:

Let me give you a hint first.

removeItem(index) takes as argument an index of the value that you want to remove.

So then when you filter an array you have to compare this index with the index of the value that you currently iterate over.

You have to change something here:

I hope it does make sense :slight_smile:

thanks i got it i just added the code return [
…state.slice(0, action.index),
…state.slice(action.index + 1, state.length)
];

1 Like

I’m glad that you got it to work :slight_smile:

Also, it could be done like this:

state.filter( (val, index) => index !== action.index )

Filter method as a second argument accepts index of the current element being processed. So then you compare this index, with the index of item you want to remove :slight_smile:

If you want to read more on filter() method, here is a great resource: Array.prototype.filter