'react filter array when user clicks elements with same values

I am trying to build simple puzzle application for my personal react project.

Basically, I have made an array with objects and map through this array to render puzzle lists.

const puzzleData = [
  { id: Math.random() * 5, value: '<main>', key: 'main' },
  { id: Math.random() * 5, value: '</main>', key: 'main' },
  { id: Math.random() * 5, value: '<section>', key: 'section' },
  { id: Math.random() * 5, value: '</section>', key: 'section' },
  { id: Math.random() * 5, value: '<nav>', key: 'nav' },
  { id: Math.random() * 5, value: '</nav>', key: 'nav' },
  { id: Math.random() * 5, value: '<footer>', key: 'footer' },
  { id: Math.random() * 5, value: '</footer>', key: 'footer' },
  { id: Math.random() * 5, value: '<aside>', key: 'aside' },
  { id: Math.random() * 5, value: '</aside>', key: 'aside' },
  { id: Math.random() * 5, value: '<h1>', key: 'h1' },
  { id: Math.random() * 5, value: '</h1>', key: 'h1' },
  { id: Math.random() * 5, value: '<p>', key: 'p' },
  { id: Math.random() * 5, value: '</p>', key: 'p' },
  { id: Math.random() * 5, value: '<span>', key: 'span' },
  { id: Math.random() * 5, value: '</span>', key: 'span' },
];

const [puzzle, setPuzzle] = useState([...puzzleData]);

<ul className={styles.puzzle}>
        {puzzle.map((item, i) => {
          return (
            <li
              key={item.id}
              onClick={() => {
                filterHandler(item.key, item.id);
              }}
              style={{ backgroundColor: color.id === item.id ? 'white' : null }}
            >
              {item.value}
            </li>
          );
        })}
      </ul>

I want my filterHandler function applied onClick to filter puzzle array when user clicks same li elements with same key value. For example, when user clicks main and /main in li elements, filter puzzle array to remove those two from the rendered elements. Below is my current filterHandler function.

const filterHandler = (key, id) => {
setPuzzle((prevState) => {
      const updated = prevState.filter(
        (item) => item.key !== key || item.id !== id
      );
      return updated;
    });

Right now, it is filtering out li element that user clicks but I want to filtering out li element when user clicks two same elements with same key values (like real puzzle game). Is there a way to apply this logic with filter method? Thanks in advance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source