Redux - Remove an Item from an Array (Spread Solution Question)

I’ve passed this lesson with various solutions, but I’m curious as to what the “spread operator solution” looks like.

I’ve seen one solution look like:

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);

I have 2 questions about this:

  1. Is this the intended solution for solving this challenge using the spread operator?
  2. How is the line
    return [...state.slice(0,action.index), ...state.slice(action.index+1, state.length)];

evaluated? I was confused at first because I read it left to right. So ...state would “spread out” the elements of state, and thus the subsequent .slice(0, action.index) should not work (because .slice() needs to be called on an array), right? But apparently the solution does work, so I’m guessing state.slice(0,action.index) is evaluated first before ... is applied? There’s some sort of order of precedence with the operators, and it’s not just evaluated left to right?

I guess I should include the link to this solution:

Thanks in advance!

slice returns a new array so that is what is being spread into the array literal.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2)); // ["camel", "duck", "elephant"]
console.log(animals.slice(0, 2)); // ["ant", "bison"]

const newOrder = [...animals.slice(2), ...animals.slice(0, 2)];
console.log(newOrder); // ["camel", "duck", "elephant", "ant", "bison"]
1 Like

I see, so going off of your example animals.slice(2) is evaluated to an array before ... is applied. I guess my confusion was due to the fact that I thought expressions were always evaluated left to right, and so I thought ...animals would be evaluated first.

Well, it has to be applied to an iterable. Otherwise, it would be a syntax error.

It wouldn’t be very useful if you were not able to spread the returned array coming from one of the array methods.


As an aside, the spread operator has a precedence of 13 (the lowest).

2 Likes

Ah, I think that aside is actually the explanation I was looking for. Thanks!

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