Skip to content

Array splice()

JavaScript Array splice() Definition

The splice () method removes, modifies, or inserts new items in the array. So it changes the contents of the array. ( changes the original array )

Syntax:

array.splice(index, howmany, item1, ….., itemX)

index (required): An integer that specifies at what position to add/remove items.
howmany(optional): The number of items to be removed.
item1, …, itemX(optional): The new item to be added to the array.

Let’s try to understand the logic with a small example.

        let cars = ["bmw", "audi", "mercedes", "toyota"];
        console.log("original cars:  " + cars);

        let arr = cars.splice(0,2,"ford","range rover")
        console.log("new cars:  "+cars)

original cars: bmw,audi,mercedes,toyota
new cars: ford,range rover,mercedes,toyota


JavaScript Array splice() Examples

Example 1

If the last parameter is not entered, it assigns the last value.

        let numberList = [ 1, 2, 3, 4, 5, 6 ];
        let arr = numberList.splice( 2 );
        console.log( numberList );

output:

[1, 2]


Example 2

        let row = ["zero", "first", "second", "third"];

        let arr1 = row.splice(-1, 1);
        console.log(row);

        let arr2 = row.splice(-5, 1);
        console.log(row)

output:

[“zero”, “first”, “second”]
[“first”, “second”]


Example 3

        let names = [ "bob", "oliver", "rick", "oliver" ];
        let arr =  names.splice( 3,2,"julia" )
        console.log( names )

output:

1[“bob”, “oliver”, “rick”, “julia”]


Example 4

        let names = [ "bob", "oliver", "rick", "oliver","alex","barry"];
        let arr = names.splice(0, names.length - 2);
        console.log( names )

output:

 [“alex”, “barry”]


Browser Support

Chrome1
Edgeyes
Firefox1
Internet Explorer5.5
Operayes
Safariyes
Android webviewyes
Chrome for Androidyes
Edge mobileyes
Firefox for Android4
Opera Androidyes

2 Comments »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: