Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
201 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here's a strange way it could be done:

const item = 5
const selection = [3, 4, 5, 6]
const itemPos = selection.indexOf(item)

if (selection.includes(item)) {
  // remove if available
  const {[itemPos]: item, ...rest} = selection

  // `rest` is now an object, so convert back to an array:
  console.log(Object.values(rest)) // [3, 4, 6]
  setSelection(Object.values(rest))
} else {
  // ...
}

Since I used const in both places, the second item is a different one, but one could remove const and wrap the expression in parentheses to reassign item (as I think you had originally requested):

let rest, item = 5
const selection = [3, 4, 5, 6]
const itemPos = selection.indexOf(item)

if (selection.includes(item)) {
  // remove if available
  ({[itemPos]: item, ...rest} = selection)
  console.log(Object.values(rest)) // [3, 4, 6]
  setSelection(Object.values(rest))
} else {
  // ...
}

But if you wanted to follow a similar pattern without using filter, you could use splice:

const item = 5
const selection = [3, 4, 5, 6]
const itemPos = selection.indexOf(item)

if (selection.includes(item)) {
  // remove if available
  const rest = [...selection] // Copy array if you still need `selection`; otherwise, we could just splice and pass `selection`
  rest.splice(itemPos, 1)
  console.log(rest)
  setSelection(rest)
} else {
  // ...
}

None of these are especially appealing compared to filter, but it should show how the approaches would work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...