yoursweater
yoursweater

Reputation: 2041

Having trouble removing an item from an array with splice

What I want to do

I want to create a toggle function that allows a user to click on or off checkboxes by either adding them to an array (my state object), or if they're already there, removing them from the array.

What I expect to happen

with the following code, if the checkbox isn't in the selected array, it should be added. If it already exists, remove it:

   if (this.state.selected.indexOf(rowNumber) == -1) {

      let tempState = this.state.selected
      tempState.push(rowNumber)

      this.setState({
        selected: tempState
      })

    } else if (this.state.selected.indexOf(rowNumber) > -1 ){

      let tempIndex = this.state.selected.indexOf(rowNumber)
      let tempState = JSON.parse(JSON.stringify(this.state.selected))
      tempState = tempState.splice(tempIndex, 1)

      this.setState({
        selected: tempState
      })

    }

My state object is a simple array.

What actually happens

When splice activates, it removes the previously clicked element and not the one I'm currently clicking on.

I'd like to know why it's not just selecting/deselecting the currently clicked checkbox. Thanks!

edit: solved below!

Here's the link with the working example: https://repl.it/@yoursweater/MemorableJitteryAustraliancurlew

Upvotes: 3

Views: 184

Answers (2)

kshetline
kshetline

Reputation: 13700

Might I just suggest a different approach? Arrays is JavaScript can handle setting non-consecutive indices, so you can start with an empty array like this:

const state = [];

...and then do something like this:

state[3] = true;

...and then you'll have an array that looks like this:

[undefined, undefined, undefined, true];

You can also then access an out-of-bounds index, and it's simply treated as undefined as well.

if (state[5]) {
  console.log('You won\'t see this.');
}
else {
  console.log('You will see this.');
}

Because of the way JavaScript arrays work, you can store and toggle your button states simply by doing:

state[rowNumber] = !state[rowNumber];

Upvotes: 0

ctring
ctring

Reputation: 106

Array.splice() removes the elements in the array in place and returns the removed elements. Since you assign tempState = tempState.splice(tempIndex, 1), tempState now contains the removed elements. You can just rewrite that line to be tempState.splice(tempIndex, 1) to fix it (no reassigning tempState).

Also instead of doing JSON parse/stringify, you can copy the array by using a = b.slice()

Upvotes: 2

Related Questions