In this brief tutorial you will learn how to insert one or more elements into an array with JavaScript.
For this we will use the splice
function.
The splice
function will not create a new array when used, but will modify the existing array. The syntax of the splice
function, included in Array elements, is as follows:
arr.splice(index, deleteElements, insertElement1, insertElement2, ..., insertElementN)
Let's start from the following example array:
const numbers = [0, 1, 2, 3, 4, 6, 9];
What we are going to do is to insert element 5 in the fifth position of the array.
To do this we would use the splice
function like this:
numbers.splice(5, 0, 5);
Now, if we do a console.log
of the array numbers, we get the following:
(8)[0, 1, 2, 3, 4, 5, 6, 9]
Now we are going to insert multiple elements, so we are going to add the values 7 and 8. In this case we simply indicate the elements to be inserted, one after the other:
arr.splice(7, 0, 7, 8);
If, again, we do a console.log
of the array numbers, we get the following:
(10)[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]