How do I remove a particular element from an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

To remove an element from an array, use the splice() method. JavaScript array splice() method changes the content of an array, adding new elements while removing old elements.

The following are the parameters −

  • index − Index at which to start changing the array.

  • howMany − An integer indicating the number of old array elements to remove. If howMany is a 0, then no elements are removed.

  • element1, ..., elementN − The elements adds to the array. If you don't specify any elements, splice simply removes the elements from the array.

You can try to run the following code to learn how to add and remove individual elements in a JavaScript array −

Example

Live Demo
<html>
   <head>
      <title>JavaScript Array splice Method</title>
   </head>
   
   <body>
      <script>
         var arr = ["orange", "mango", "banana", "sugar", "tea"];

         var removed = arr.splice(2, 0, "water");
         document.write("After adding 1: " + arr );
         document.write("<br />removed is: " + removed);

         removed = arr.splice(3, 1);
         document.write("<br />After adding 1: " + arr );
         document.write("<br />removed is: " + removed);
      </script>
   </body>
   
</html>

Output

After adding 1: orange,mango,water,banana,sugar,tea
removed is: 
After adding 1: orange,mango,water,sugar,tea
removed is: banana
raja
Published on 25-Jan-2018 12:31:34
Advertisements