Skip to content

JavaScript Remove specific element from Array | Example code

  • by

First, find the index of the array element you want to remove using the indexOf method, 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 or 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

Your email address will not be published. Required fields are marked *