In this article we will learn how to use splice method in Javascript. The JavaScript splice()
method allows you to modify an array by adding or removing elements from it.
Splice method in Javascript
The splice()
method takes three arguments:
- Index: The index at which to start changing the array. If negative, the index will be counted from the end of the array.
- Delete count: An integer indicating the number of old array elements to remove.
- Element(s): The element(s) to add to the array.
Below are some examples of how to use the splice()
method:
- Removing elements from an array:
let fruits = ["apple", "banana", "orange", "mango"];
fruits.splice(1, 2); // Removes "banana" and "orange" from the array
console.log(fruits); // Output: ["apple", "mango"]
- Adding elements to an array:
let numbers = [1, 2, 3, 4, 5];
numbers.splice(2, 0, 6, 7); // Inserts 6 and 7 at index 2
console.log(numbers); // Output: [1, 2, 6, 7, 3, 4, 5]
- Replacing elements in an array:
let colors = ["red", "green", "blue"];
colors.splice(1, 1, "yellow"); // Replaces "green" with "yellow"
console.log(colors); // Output: ["red", "yellow", "blue"]
- Removing elements from the end of an array:
let letters = ["a", "b", "c", "d"];
letters.splice(-2); // Removes "c" and "d" from the end of the array
console.log(letters); // Output: ["a", "b"]
- Removing all elements from an array:
let myArray = [1, 2, 3, 4, 5];
myArray.splice(0, myArray.length);
console.log(myArray); // Output: []
- Removing a single element from an array:
let myArray = [1, 2, 3, 4, 5];
myArray.splice(2, 1); // Removes the element at index 2
console.log(myArray); // Output: [1, 2, 4, 5]
- Adding multiple elements to an array:
let myArray = [1, 2, 3, 4, 5];
myArray.splice(2, 0, 6, 7, 8); // Adds elements 6, 7, and 8 at index 2
console.log(myArray); // Output: [1, 2, 6, 7, 8, 3, 4, 5]
- Reversing the order of elements in an array:
let myArray = [1, 2, 3, 4, 5];
myArray.splice(0, myArray.length, ...myArray.reverse());
console.log(myArray); // Output: [5, 4, 3, 2, 1]
- Using
splice()
to flatten an array of arrays:
let nestedArray = [[1, 2], [3, 4], [5, 6]];
let flatArray = [].concat.apply([], nestedArray);
console.log(flatArray); // Output: [1, 2, 3, 4, 5, 6]
These were few examples of the many ways that you can use the splice()
method to manipulate arrays in JavaScript. Hope you liked the short explanation. 🙂