Remove-an-item-from-an-array

Remove-an-item-from-an-array
0

Tell us what’s happening:
can somebody explain me why it takes upto action.index and late to state.length?
cant it be ( …state.slice(0, state.length))

Your code so far


const immutableReducer = (state = [0,1,2,3,4,5], action) => {
switch(action.type) {
  case 'REMOVE_ITEM':
  return
    
    ...state.slice(0, action.index),
      ...state.slice(action.index + 1, state.length)
  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_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36.

Challenge: Remove an Item from an Array

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

does (index) really needs the curly brackets?

First, regardless of anything else, your syntax is wrong. ... takes something iterable (eg an array) and yields the values back one by one. But you need to put those values into some container, the spread syntax doesn’t make any sense on its own. Like:

const arr = [1,2,3]
const copy = [...arr]

So for copy, the values from arr (...arr) are put into a new array ([]). Two arrays:

const arr1 = [1,2,3]
const arr2 = [4,5,6]
const joinedCopy = [...arr1, ...arr2]

In your code, you aren’t putting the values from the slices into anything, so you’ll get a syntax error.


Then with regards to slice, the way the item is being removed is to take the values from index 0 to the item you want removed, and join those together with the values from the index just after until the end of the array. In effect, nothing is being removed: you are creating a new array with the values up the one you don’t want, joined to the values from after the one you don’t want to the end.

A slice of the array from index 0 to the end of the array is just the entire array.