DevGe
DevGe

Reputation: 1449

How to splice the specific index using the IndexOf method of javascript

I have module where I need to uncheck or check the data using checkbox. Now the problem is I need to slice the push value if the user uncheck it based on the target value. Currently when i try to console log the index it result -1 meaning: "it is not present" I will show you guys my sample code and sample attached image for the reference to make more detailed..

Code:

        var array = [...this.state.checkboxVal]; 

        
        console.log(e.target.value,"my index")

        var index = array.indexOf(parseInt(e.target.value));

        console.log(index);

        if (index > -1) {
            array.splice(index, 1);
            
            await this.setState({ checkboxVal: array });
        }


        console.log(this.state.checkboxVal);

The Expected Output: The Index 1 should be remove

Output

Upvotes: 1

Views: 252

Answers (3)

Drew Reese
Drew Reese

Reputation: 202751

The issue is that you are comparing incompatible types, "number" vs "array", so a match can never be found.

If you are simply wanting to remove an element from an array in state in React, using a Array.prototype.filter is a common pattern.

const targetValue = Number(e.target.value);
this.setState(prevState => ({
  checkboxVal: prevState.checkboxVal.filter(([val]) => val !== targetValue),
}));

The filter callback ([val]) => val !== targetValue is taking the array element and uses destructuring assignment to get the value stored in index 0 and name it val and then return only the elements with a val not equal to the event's target value.

Upvotes: 1

Showrin Barua
Showrin Barua

Reputation: 1795

In your array, every element is an array (for example: [30, "2021-05-17"]). But you are now checking only the value whether it's present or not. You have to check [30, "2021-05-17"] whether it's present or not.

Here's an example:

const arr = [[30, "2021-05-17"], [50, "2021-05-17"], [20, "2021-05-17"]];
const valueToDelete = 20;

const newArray = arr.filter(item => item[0] !== valueToDelete);

console.log(newArray);

In your case this would be:

var array = [...this.state.checkboxVal]; 

const newArray = array.filter(item => item[0] !== parseInt(e.target.value));

console.log(newArray);

this.setState({ checkboxVal: newArray });

Hope this will help you brother. Thank you. :)

Upvotes: 1

Ayzrian
Ayzrian

Reputation: 2465

The problem is that you are storing an array of arrays so you are trying to compare number to array and apparently it will return -1. To solve this you can use findIndex function in the following way.

        var value = parseInt(e.target.value);
        var index = array.findIndex((element) => element[0] === value);

NOTE: Please use let and const these are latest way to define your variables.

Upvotes: 2

Related Questions