Home > Software design >  How to remove one item from an array if matched?
How to remove one item from an array if matched?

Time:10-26

I have something like this

mainArray ["a","a","b","c","d"]

And once user click one of these letters I'm pushing it to a new array and hidden that selected item from main array, but the problem here is that if I select "a" letter from array both "a" will be hidden, how can I fix that?

this is what I've tried

style={[newArray.find((item) => item === mainArray[i])
        ? styles.hideItem
        : styles.showItem]}

Once newArray Received it will be hidden from mainArray

CodePudding user response:

Use indexOf() to get the position of the first match. Then you can use splice() to remove it.

let index = mainArray.indexOf(letter);
if (index != -1) { // if found
    newArray.push(mainArray[index]); // push to new array
    mainArray.splice(index, 1); // and remove from main array
}
  • Related