A succint, one line answer to "Redux: Remove an Item from an Array"?

I’d include a link to the exercise, but apparently I’m not allowed to use links yet?

Anyway, so, for the “Redux: Remove an Item from an Array” exercise, I did the following,

    let newArray = [...state];
    newArray.splice(action.index,1);
    return newArray;

Which works fine.

My question, however, is there a more succinct way to do this? Some way to remove an item from the array and return the new array in one line? Something like [...state].splice(action.index,1) is just going to return the removed item, not the array itself.

1 Like

You can do something like this instead.

return state.filter((_, index) => index !== action.index);

1 Like

Thank you. That makes sense.

Is the underscore used to indicate that the variable isn’t being used or something like that?

2 Likes

Yep you are right :slight_smile:

1 Like

Here’s an alternative that doesn’t use .filter. I personally dislike the idea of using filter, as it will iterate over the entire array just to “remove” 1 item in the end. I think going over the entire array is required anyways to “copy” it over all the item references (or values) to the new array so I think this isn’t really that big of a deal haha. But it is something to remember in general when using most of the array functions. (filter, reduce, map)

const removeFromArr = (arr, index) => [
  ...arr.slice(0, index),
  ...arr.slice(index + 1, arr.length)
];

Here’s the pen to play around in.

Finally, I want to point out its really easy to get splice and slice mixed up, one gets you a slice, which is a thing (so it gives you a new array of the sliced data, without touching the original array ). splice is an action, where you splice the array, which is an action, so you are changing the data in the original array via reference.

Happy coding :smiley:

1 Like