Skip to content

Instantly share code, notes, and snippets.

@MirzaLeka
Last active July 16, 2023 19:04
Show Gist options
  • Save MirzaLeka/c16fd4cd5815a247ff2349a559d0635f to your computer and use it in GitHub Desktop.
Save MirzaLeka/c16fd4cd5815a247ff2349a559d0635f to your computer and use it in GitHub Desktop.
Find and remove item from an array using ES6/7

Remove Item from Array in JavaScript

Quite simple, really! Please keep in mind that ES7 might not be compatible with IE.

    const myArray = [];

        let addToArray = (newItem) => {
            
            if ( myArray.includes(newItem) ) {
                myArray.splice(myArray.findIndex(index => index == newItem), 1); // if element is in an array, find index & remove element  
                // number 1 in the end is to tell JS to remove exactly 1 element
                // without it, we would wipe array elements all the way to the end
            } else {
                myArray.push(newItem);    // else push it to array
            }
    
        }

Special thanks to Stack Overflow

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment