Free programming examples and instructions

Remove item from array - Javascript

Demo and code for how to remove an item from array in javascript using splice() function.

by Athil

Posted on 27 Jun 2018 Category: Javascript Views: 1525

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


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.

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 the item to an existing array with position and remove no if items,

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

for example

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

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.

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