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 rest. 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.
Is it possible to extract a specific item from an array and unpack the rest of the elements to a variable by using destructuring assignment ?