JavaScript Remove specific element from Array | Example code

Find the index of the array element you want to remove using indexOf, and then remove that index (specific value/element) with a splicing method (splice()) in JavaScript.

JavaScript Remove specific element from Array Example

HTML example code.

Note: The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

<!DOCTYPE html>
<html>
<body>

  <script>
    var colors = ["red","blue","black","green"];

    console.log(colors);

    function remEle(v){

      const index = colors.indexOf(v);
      if (index > -1) {
        colors.splice(index, 1);
      }
    }

    //remove color red
    remEle("red")
    console.log(colors); 
  </script>

</body>
</html>

Output:

JavaScript Remove specific element from Array

Do comment if you have any doubts and suggestions on this JS Array topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.