JavaScript – How to remove certain element from Array

In JavaScript, we can combine indexOf() and splice() to remove a certain element from an Array.


        var array = [1, 2, 3, 4, 5];
        console.log(array)

        // I want remove num 4, find the index first, -1 if it is not present.
        var index = array.indexOf(4);
        if (index > -1) { // found
            array.splice(index, 1);
        }

        // array = [1, 2, 3, 5];
        console.log(array);


        var lang = ['java', 'node js', 'javascript', 'pyhton'];
        console.log(lang)

        // I want remove node js
        var index = lang.indexOf(`node js`);
        if (index > -1) {
            lang.splice(index, 1);
        }

        //lang = ['java', 'javascript', 'pyhton'];
        console.log(lang);

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

avatar