Tell us what’s happening:
Im not sure why this is not passing the test. Am I not allowed to use filter() on this challenge?
any feedback will be appreciated.
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 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36.
As JM-Mendez mentioned your filter function is wrong. Filter method works for “value” filtering not index.
To filter the array by index you have to use:
Your solution is way more consice than mine.
My original solution state.slice(0,action.index).concat(state.slice(action.index+1)).
Your solution corrected state.filter((v,i)=>i!=action.index)
I’m gonna try and explain because it took me a while to get it too. So let’s say you want to send an action to remove item 3, so the result is [0,1,2,4,5].
So with slice you slice up until 3: arr.slice(0, 3), which gives you [0,1,2]. Then you do arr.slice(4) which gives you [4,5] because it goes until the end of the array from where you tell it to start.
And the +1 you’re seeing is where it continues from, in this case 3+1 =4 (because we want to eliminate 3).
Finally you need destructuring to “glue” the arrays back together, hence the …state etc.
Good going @Fourleaftayback In the last .slice() used, the second argument - state.length - is not needed per the MDN
" If end is omitted, slice extracts through the end of the sequence ( arr.length )."