UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Remove items from array

Demo and Code for how to remove an item from array using javascript

by Athil


Posted on 07 Jul 2017 Category: Javascript Views: 231

Edited on 10 Aug 2017



DEMO

Hi, Here I am going to show how to remove an item from an array in javascript using array index.

Syntax of array splice

   arrayname.splice(<index>, <no_of_items>);

Array splice method is used for both add/remove items from an array by index.

Example for Removing Item from array using array splice

  if (i > -1) { // Where i is the index and dataArray is array name
                   dataArray.splice(i, 1);
            }

Example for adding item in array using array splice

var arrayname= ["Car", "Bike", "Truck", "Scooter"];
arrayname.splice(2, 0, "Train", "Bus"); // Where 2 is to add second index two items by removing 0 items

Demo Code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title> Demo for array splice</title>
</head>
<body>
    <h1> Demo for array splice </h1>

    <button onclick="Removeitem();"> Remove Item
        </button>
    <button onclick="addditem();"> Add Item
        </button>

</body>

      <script type="text/javascript">

          function Removeitem() {
              var arrayname = ["Car", "Bike", "Truck", "Scooter"];
              if (1 > -1) { // Where i is the index and dataArray is array name
                  arrayname.splice(1, 1);
              }
              alert(JSON.stringify(arrayname));

          }
          function addditem()
          {
              var arrayname = ["Car", "Bike", "Truck", "Scooter"];
              arrayname.splice(2, 0, "Train", "Bus");
              alert(JSON.stringify(arrayname));
          }

        </script>
</html>

 



Leave a Comment:


Advertisement