Seemed quite intuitive to me, but turns out that's not how things work! The goal is to remove the passed element if it exists and return the remainder. I know there's a number of ways of achieving this - including filter
: const rest = selection.filter(i => i !== item)
- but, as I said, thought this approach would be a thing - as it is for objects/key:value pairs
.
if (selection.includes(item)) {
// remove if available
const [item, ...rest] = selection;
setSelection(rest)
} else {
// ...
}
The way destructuring
works is it assigns the first
element of selection
to item and assigns the rest of the items to rest
- an array. Which is correct - that's how things work, from my understanding at least.
What's the possibility of "injecting" item
's value into the destructuring assignment, and not having to treat it as new variable holding the first element of the array?