Remove item from an Array when clicking in a option

I have a Javascript array named activeFilters with the following values:

var activeFilters = [
    ['Tom Brady', 'Aaron Rodgers', 'Patrick Mahomes'],
    ['Post Game', 'Status']
];

I also have a menu list with all the values gathered in an unordered list:

<ul id="list">
    <li>Tom Brady</li>
    <li>Post Game</li>
    <li>Aaron Rodgers</li>
    <li>Patrick Mahomes</li>
    <li>Status</li>
</ul>

My main goals is: when users click in one of the <li> options to remove this value from the array.

19 thoughts on “Remove item from an Array when clicking in a option”

  1. const activeFilters = [
      ['Tom Brady', 'Aaron Rodgers', 'Patrick Mahomes'],
      ['Post Game', 'Status']
    ];
    
    const removeActiveFilterItem = (evt) => {
      const name = evt.currentTarget.textContent.trim();
      activeFilters.forEach((arr) => {
        const i = arr.findIndex(x => x === name);
        if (i > -1) arr.splice(i, 1);
      });
      evt.currentTarget.remove();
    }
    
    const EL_ListLIs = document.querySelectorAll("#list li");
    EL_ListLIs.forEach(EL => EL.addEventListener("click", removeActiveFilterItem));
    <ul id="list">
      <li>Tom Brady</li>
      <li>Post Game</li>
      <li>Aaron Rodgers</li>
      <li>Patrick Mahomes</li>
      <li>Status</li>
    </ul>
    Reply
  2. <script>
      var activeFilters = [
        ['Tom Brady', 'Aaron Rodgers', 'Patrick Mahomes'],
        ['Post Game', 'Status']
    ];
    // Select all the lis 
    const lis = document.querySelectorAll("li");
    lis.forEach((li) => {
     // Add event listener on each one of them with the callback function
      li.addEventListener("click",function() {
    // Flat your arrays
        activeFilters = activeFilters.flat();
    // Get the text from clicked li
        const textToRemoveFromArray = this.textContent;
       // Get the index in the array of the name
       const indexOfClickedName = activeFilters.findIndex((name) => textToRemoveFromArray === name);
    // Splice from array at the index position, 1
       activeFilters.splice(indexOfClickedName,1);
      })
    })
    </script> 
    
       
    
    Reply

Leave a Comment