UncleCoder.com

UncleCoder.com

Free programming examples and instructions

Adding item to an array by position using array splice() - Javascript

Demo and code for adding item to an array by position using splice() in Javascript

by Athil


Posted on 27 Jun 2018 Category: Javascript Views: 31

Edited on 01 Jul 2019


Here I am going to show how to remove an item from javascript array using splice() method.

DEMO

 

Add Item


arrayname.splice(index, no_of_items_replace, "Train", "Bus");
              

using this method we can add items to an array to any index, This code will add an item to an existing array with position and remove no if items,

for example

arrayname.splice(2, 0, "Train", "Bus");

The first parameter is index no, second is no of items to replace and from third is items to add in the array,

if we are giving code like this, this array will add two items without any replace after the second index because we give the first parameter is 2 and second parameter is 0 and from third, we give two values.

Remove item

arrayname.splice(index, no_of_items);

Here array name is the name of array and splice having two parameters to remove an item from an array. The first parameter is the index of the item to remove and the second parameter is no if items to remove from the index.

Full Demo code

HTML

<!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>

      
</html>

Javascript

<script type="text/javascript">

          function Removeitem() {
              var arrayname = ["Car", "Bike", "Truck", "Scooter"];
               arrayname.splice(1, 2);
              
              alert(JSON.stringify(arrayname));

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


        </script>

 



Leave a Comment: