Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu March 20, 2023 › #Array #HowTo

JavaScript insert multiple elements into array at index

You may already know how to add a new element at the end of an array, but did you know that you can also insert multiple elements into an array at a specific index?

Today I want to talk about one of the cool features in JavaScript that you can use when inserting multiple elements into an array.

Example 1 : Using the splice() method. #

The first way is by using the splice() method. This method allows us to add one or more elements at any position in an array simply by specifying the starting index and then providing all of our desired values as additional arguments. For example :

<script>
 let myArray = [1, 2, 3, 4]
 myArray.splice(4,0,5,6)
 console.log(myArray)
 // output : [1, 2, 3, 4, 5, 6]
</script>
The splice() method takes three arguments: starting index, number of items removed (which should be 0 if no items are being removed), and any additional values which will be added as new entries in the specified position.

Example 2 : using the unshift() method #

Finally there’s also unshift() method. unshift() works similarly as splice(), but instead of adding new items after a specified element it adds them before said element instead – making its use slightly more limited than either Splice Syntax mentioned earlier.. To use unshift(), simply pass in your desired value/values separated with commas directly following your targetted index number like this:

<script>
 let myArray = [1, 2, 3, 4]
 myArray.unshift(5,6)
 console.log(myArray)
 // output : [5, 6, 1, 2, 3, 4]
</script>

And there you have it - two easy methods for inserting multiple elements into an array at any given position using JavaScript! I hope this helps make manipulating arrays just a little bit easier.

save
listen
AI Answer
Write Your Answer
loading
back
View All