techStackGuru

JavaScript Array splice


Using JavaScript's splice() method, array elements can be added, removed, or replaced. There are three parameters in splice(): start, deleteCount, and optionally item1, item2, etc.

Syntax:

array.splice(index, removeElements, addElements..)

index: Required. Add or remove items by index (position). The array starts at the end when the value is negative.

removeElementsOptional. Amount of items to be removed.

addElementsOptional. Amount of items to be added.

Example:

const colors = ['red', 'green', 'blue', 'yellow'];

// Remove 'green' and 'blue' from the array starting at index 1
const removed = colors.splice(1, 2);
console.log(removed); // Output: ['green', 'blue']
console.log(colors); // Output: ['red', 'yellow']

Inserting elements:

Example 1

const fruits = ["apple", "banana", "orange"];

// Insert "mango" after "banana" at index 1
fruits.splice(1, 0, "mango");

console.log(fruits); // Output: ["apple", "banana", "mango", "orange"]

Example 2

const colors = ['red', 'yellow'];

// Add 'green' and 'blue' to the array starting at index 1
colors.splice(1, 0, 'green', 'blue');
console.log(colors); // Output: ['red', 'green', 'blue', 'yellow']

Deleting elements:

Example 1

const numbers = [1, 2, 3, 4, 5];

// Remove element at index 2 (which is 3)
numbers.splice(2, 1);

console.log(numbers); // Output: [1, 2, 4, 5]

Example 2

const numbers = [1, 2, 3, 4, 5];

// Remove element from index 2
numbers.splice(2);

console.log(numbers); // [ 1, 2 ]

Replacing elements:

const colors = ["red", "green", "blue", "purple"];

// Replace element at index 1 (which is "green") with "yellow"
colors.splice(1, 1, "yellow");

console.log(colors); // Output: ["red", "yellow", "blue", "purple"]