Onjsdev

Share


JavaScript Splice() Method


By onjsdev

Jan 4th, 2024

The javascript splice() method allows you to add or remove elements from an array. This method modifies the original array and returns the removed elements if they exist.

Syntax

The syntax for using the splice() method is as follows:

array.splice(start, deleteCount, item1, item2, ...)
  • start: The index at which to start changing the array. If start is negative, it specifies an offset from the end of the array. For example, -2 means the second-to-last element in the array.
  • deleteCount: It indicate the number of elements in the array to remove from start.
  • item1, item2, etc.: The elements to add to the array, beginning at the start index.

Examples

Here are some examples of using the splice() method:

Removing Elements from an Array

In the example below, we start removing the element at index 2 and remove 1 element.

let fruits = ['apple', 'banana', 'orange', 'mango'];
let removedFruit = fruits.splice(2, 1); // Removes the element at index 2 (orange)
console.log(fruits); // Output: ['apple', 'banana', 'mango']
console.log(removedFruit); // Output: ['orange']

Adding Elements to an Array:

If you add element instead of removing, so you can set the second parameter 0., And other elements is added to the function in a row.

Here is an example:

let numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 0, 6, 7); // Adds 6 and 7 at index 2
console.log(numbers); // Output: [1, 2, 6, 7, 3, 4, 5]

Replacing Elements in an Array:

The following example shows that if your second parameter is not zero and you attach some elements to the function. The split method performs replacing action. The function below starts replacing two elements at index 1.

let colors = ['red', 'green', 'blue', 'yellow'];
colors.splice(1, 2, 'orange', 'purple'); // Replaces 'green' and 'blue' with 'orange' and 'purple'
console.log(colors); // Output: ['red', 'orange', 'purple', 'yellow']

Conclusion

The splice() is a powerful method for manipulating arrays in JavaScript. By understanding how it works and experimenting with different parameters, you can easily add, remove or replace elements in arrays.

Here are some guides on Javascript array methods:

Thank you for reading.