Javascript Array splice() Method with Intelligible Examples

In this article, we will discuss splice() method for JavaScript array.

Javascript array splice():

  • splice() method adds and/or removes elements from an array.
  • splice() method changes the original array.

Syntax 1

array.splice(index);

Example 1


var array = ['b', 'c', 'd', 'c', 'b'];

// All elements except the first element will be removed
array.splice(1);
console.log(array);
// output: ["b"]

Example 2


var array = ['b', 'c', 'd', 'c', 'b'];

// All elements except the first 3 elements will be removed
array.splice(3);
console.log(array);
// output: ["b", "c", "d"]

Syntax 2

array.splice(index, numberOfElements);

Example


var array = ['b', 'c', 'd', 'c', 'b'];

// It will remove 3 elements starting from index 2
array.splice(2, 3);
console.log(array);
// output: ["b", "c"]

Syntax 3

array.splice(index, numberOfElements, addItem1, addItem2,..., addItemN);

Example 1


var array = ['b', 'c', 'd', 'c', 'b', 'e'];

// It will remove 3 elements starting from index 2
// and add 'X' and 'Y' at index 2 and 3
array.splice(2, 3, 'X', 'Y');
console.log(array);
// output:  ["b", "c", "X", "Y", "e"]

Example 2


var array = ['b', 'c', 'd', 'e', 'f', 'g', 'h'];

// It will add 'X' and 'Y' at index 2 and 3
// none of the elements will be removed
array.splice(2, 0, 'X', 'Y');
console.log(array);
// output:  ["b", "c", "X", "Y", "d", "e", "f", "g", "h"]

Leave a Reply

avatar
  Subscribe  
Notify of