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: 1313

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



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


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

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




<script type="text/javascript">

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

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



Leave a Comment:

Click here to register

Popular articles