0

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

  • 1
    You should find by the index of the letter that was clicked, not the letter itself. – kelsny Oct 25 '22 at 19:53
  • Can you provide more information pls , if so I can approve as a correct answer? – Hakar Yousef Oct 25 '22 at 19:56
  • I don't know how your code works, so I cannot provide a concrete example. You would have to edit your question with the code that shows what `mainArray` and `newArray` is, and also what `i` is. – kelsny Oct 25 '22 at 19:59
  • Sorry that was happened by mistake, check above code now, Array was mainArray – Hakar Yousef Oct 25 '22 at 20:02
  • I get a tiny little bit worried about mutating arrays when I see the word _React_ in the question. Just in case it is the intent of any passers-by to attempt to do this, here's my gentle but paranoid reminder to be careful not to mutate React state. See also, [the React way](https://stackoverflow.com/questions/36326612/how-to-delete-an-item-from-state-array). – Wyck Oct 25 '22 at 20:25

1 Answers1

1

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
}
Barmar
  • 741,623
  • 53
  • 500
  • 612