JavaScript - Insert Multiple Elements in JS Array
Last Updated :
15 Nov, 2024
Improve
These are the following ways to insert multiple elements in JavaScript arrays:
1. Using bracket Notation(Simple and Efficient for Small Array)
The Bracket can be used to access the index of the given array and we can directly assign a value to that specific index.
let a = [2, 3, 4];
a[3] = 1;
a[4] = 5;
console.log(a);
Output
[ 2, 3, 4, 1, 5 ]
2. Using splice() Method (Efficient for Large Array)
The splice() method can be used to insert elements to the given array, as it takes parameter where you have to add the position where you want to insert the element, the number of elements you want to remove(in this cse it is 0 as we are adding elements) and then the value that you want to insert.
let a = [10, 20, 30, 40];
a.splice(a.length, 0, ...[50, 60, 70]);
console.log(a);
Output
[ 10, 20, 30, 40, 50, 60, 70 ]
3. Using spread Operator(Efficient for Large Array)
This method creates a new array to insert elements. The JavaScript spread syntax (...) can be used to add multiple elements in the JS array. we can directly assign the array values to the new array.
let a1 = [2, 3];
// Inserts 0 at the start
let a2 = [0, 1, ...a1];
console.log(a2);
// Inserts 4,5 at the end
let a3 = [...a1, 4, 5];
console.log(a3);
Output
[ 0, 1, 2, 3 ] [ 2, 3, 4, 5 ]