Vaidikalaya

Array Splice Method


The splice method in JavaScript/Node is a powerful way to add, remove, and replace elements in an array. It changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

Syntax

array.splice(start, deleteCount, item1, item2, ...);

Examples

Removing Elements

To remove elements from an array, specify the 'start' index and the 'deleteCount'.

let arry=['a','b','c','d'];

let res=arry.splice(1,1); // Starts at index 1, removes 1 element (that is b)

console.log(arry);  //original array after removing [ 'a', 'c', 'd' ]
console.log(res);  //removed element [b]

/*Output
    [ 'a', 'c', 'd' ]
    [ 'b' ]
*/

Adding Elements

To add elements to an array, specify the start index, a deleteCount of 0, and the elements to add.

let arr = ['a', 'b', 'c'];
let res=arr.splice(1, 0, 'x', 'y');  // Starts at index 1, removes 0 elements, adds 'x' and 'y'
console.log(arr);                   // ['a', 'x', 'y', 'b', 'c']
console.log(res);                  // []

/*Output
    ['a', 'x', 'y', 'b', 'c']
    []
*/

Replacing Elements

To replace elements in an array, specify the start index, the deleteCount, and the elements to add.

let arr = ['a', 'b', 'c', 'd'];
let res=arr.splice(2, 2, 'x', 'y');  // Starts at index 2, removes 2 elements, adds 'x', 'y'
console.log(arr);                   // ['a', 'b', 'x', 'y',] (replace c, d to x, y)
console.log(res)                   // [ 'c', 'd' ]

/*Output
    [ 'a', 'b', 'x', 'y' ]
    [ 'c', 'd' ]
*/

Removing All Elements from a Certain Index

If deleteCount is not specified, all elements from the start index to the end of the array will be removed.

let arr = ['a', 'b', 'c', 'd', 'e'];

let res=arr.splice(2);        // Starts at index 2, removes all elements till the end
console.log(arr);            // Output: ['a', 'b']
console.log(res)            // [ 'c', 'd', 'e']

/*Output
    [ 'a', 'b' ]
    [ 'c', 'd', 'e' ]
*/

The splice method is versatile, allowing for various operations on an array such as adding, removing, or replacing elements. It directly modifies the original array and can also return the removed elements, making it a powerful tool for array manipulation in JavaScript and Node.js.