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

Edited on 25 Jul 2018


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">
    <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"];
              if (1 > -1) { // Where i is the index and dataArray is array name
                  arrayname.splice(1, 1);

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



Leave a Comment: