JavaScript: Array Splice Example

By Xah Lee. Date: . Last updated: .

Array.prototype.splice is the general way to add or remove elements of a array, at any index position.

splice is a function, and is a property of Array.prototype object.

You can use it to:

splice modifies the array variable.

splice returns a array of removed elements, or empty array if none removed.

Syntax:

ES5 §15#sec-15.4.4.12

Delete Tail

// example of array splice, 1 argument form
var uu = [0,1,2,3,4,5];
var rs = uu.splice(2);          // removed rest starting at index 2
console.log(uu);                // [ 0, 1 ] the new value
console.log(rs);                // [ 2, 3, 4, 5 ]  removed items

Delete N Items at a Index

// example of array splice, 2 arguments form

var aa = [0,1,2,3,4,5];
var returnValue = aa.splice(2,3);          // start at index 2, removed 3 items

console.log(aa);                // [ 0, 1, 5 ] the new value
console.log(returnValue);       // [ 2, 3, 4 ] removed items

Insert Element to Array

Example of adding element to array:

// example of adding element to array

var uu = [0,1,2,3,4,5];
var rs = uu.splice(2, 0, "b");   // add "b" before index 2
console.log(uu);                // [ 0, 1, 'b', 2, 3, 4, 5 ]
console.log(rs);                // [] removed items
// example of adding array to array
// if you add a array, it won't be flattened

var uu = [0,1,2,3];

uu.splice(2, 0, [88,99]);   // add [88,99] before index 2

console.log(uu);                // [ 0, 1, [ 88, 99 ], 2, 3 ]

Replace a Slice (Delete and Add)

// example of array splice, 3 arguments form
var uu = [0,1,2,3,4,5];
var rs = uu.splice(2,3, "a");   // start at index 2, removed 3 items, add "a"
console.log(uu);                // [ 0, 1, 'a', 5 ] the new value
console.log(rs);                // [ 2, 3, 4 ] removed items

Splice Insert Without Nesting

if you have a function that returns a array, and you need to call this function to insert into a array but without creating a nested array. Here's how:

// array splice insert without nesting

// you have a function that returns a array.
// you need to use this function to insert elements
function addEle () { return ["a","b"]; }

// your array
var tt = [1,2,3,4];

// the index to insert at
var i = 1;

// number of element to delete before insert
var d = 0;

// insert without creating nesting
Array.prototype.splice.apply(tt, [i, d].concat(addEle()));

console.log(tt);
// [ 1, 'a', 'b', 2, 3, 4, 5 ]

In ES2015, you can use the “spread operator” of 3 dots, which basically removes the bracket:

myArray.splice( i, d, ... addEle());

Do Not Use Delete Operator to Remove Element

Warning: Don't use delete to remove elements in a array, because that creates a sparse array. 〔➤see JavaScript: Sparse Array

back to JavaScript: Array Methods

Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.