UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Adding item to an array by index

Demo and Code for how to add an item by index number.

by Athil


Posted on 08 Jul 2017 Category: Javascript Views: 172

Edited on 10 Aug 2017



DEMO

Hi, Here I am going to show how to add an item to an array by any position 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.

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

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);
            }

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