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 ?
Here's a strange way it could be done:
Since I used
constin both places, the seconditemis a different one, but one could removeconstand wrap the expression in parentheses to reassignitem(as I think you had originally requested):But if you wanted to follow a similar pattern without using
filter, you could usesplice:None of these are especially appealing compared to
filter, but it should show how the approaches would work.