How to use the JavaScript array splice method with the third parameter as an array?

Estimated read time 1 min read

The splice() method in JavaScript allows you to add or remove elements from an array. The third parameter in the splice() method is the number of elements to remove. However, if you pass an array as the third parameter, it will insert the elements of that array into the original array at the specified index.

Here’s an example of using splice() with an array as the third parameter:

let myArray = [1, 2, 3, 4, 5];

let newArray = [6, 7];

myArray.splice(3, 0, ...newArray);

console.log(myArray); // Output: [1, 2, 3, 6, 7, 4, 5]

In the example, splice() is called on the myArray array with 3 as the first parameter (the index to insert the elements), 0 as the second parameter (the number of elements to remove), and newArray as the third parameter (the array to insert).

The ... operator is used to spread the elements of newArray into the splice() method, so that the individual elements are inserted into the myArray array instead of the array as a whole.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply