- JavaScript: How to Insert Elements into a Specific Index of an Array
- Adding Elements to the Start of an Array
- Adding Elements to the End of an Array
- Using the Last Index of the Array
- The push() Method
- The concat() Method
- Free eBook: Git Essentials
- Adding Elements Anywhere in an Array
- Conclusion
- Array.prototype.push()
- Try it
- Syntax
- Parameters
- Return value
- Description
- Examples
- Adding elements to an array
- Merging two arrays
- Calling push() on non-array objects
- Using an object in an array-like fashion
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
JavaScript: How to Insert Elements into a Specific Index of an Array
An array is a linear data structure and arguably one of the most popular data structures used in Computer Science. Modifying an array is a commonly encountered operation. Here, we will discuss how to add an element in any position of an array in JavaScript.
An element can be added to an array at three places:
Let’s get started by adding elements to the beginning of an array!
Adding Elements to the Start of an Array
The unshift() method in array objects adds one or more elements to the start of an array. When executed, it also returns the new length of an array:
const startArray = [3, 4, 5]; const newLength = startArray.unshift(2); console.log(newLength); console.log(startArray); startArray.unshift(-1, 0, 2); console.log(startArray);
Which gives us the expected output:
4 [ 2, 3, 4, 5 ] [ -1, 0, 2, 2, 3, 4, 5 ]
Adding Elements to the End of an Array
Using the Last Index of the Array
To add an element to the end of an array, we can use the fact that the length of an array is always one less than the index.
Say, the length of an array is 5, then the last index at which the value will be 4. So, we can directly add the element at the last+1 index. Let us take a look:
const indexArray = [1, 2, 3]; console.log(indexArray.length); console.log(indexArray[2]); console.log(indexArray[3]); indexArray[indexArray.length] = 4 console.log(indexArray);
Running this in a JS console displays:
The array is 3 in length, and the 2nd element is 3 . There is no 3rd element, so we’re greeted with undefined . Finally, at that position, we insert the value of 4 .
The push() Method
The push() method of an array appends one or more elements to the end of it. Just like unshift() , it also returns the new length of the array:
const pushArray = [1, 2, 3] const newLength = pushArray.push(4, 5, 6, 7); console.log(newLength); console.log(pushArray);
Running the above code will display this:
The concat() Method
Merging or joining of two or more arrays is achieved by an array’s concat() method. It creates a new copy of the output and does not affect the original arrays. Unlike the previous methods, it returns a new array. The values being concatenated always come at the end of the array using the method.
We can concatenate an array with another array:
const example1Array1 = [1, 2, 3]; const valuesToAdd = [4, 5, 6]; const example1NewArray = example1Array1.concat(valuesToAdd); console.log(example1NewArray); console.log(example1Array1);
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
We can concatenate an array with a sequence of values:
const array = [1,2,3]; const newArray = array.concat('12', true, null, 4,5,6,'hello'); console.log(array); console.log(newArray);
Running the above code will log this to our consoles:
[ 1, 2, 3 ] [ 1, 2, 3, '12', true, null, 4, 5, 6, 'hello' ]
We can concatenate an array with multiple arrays:
const array1 = [1, 2, 3]; const array2 = [4, 5, 6]; const array3 = [7, 8, 9]; const oneToNine = array1.concat(array2, array3); console.log(oneToNine);
When executed, the above code prints a list of numbers from 1 to 9:
Adding Elements Anywhere in an Array
Now we will discuss a masterstroke method that can be used to add an element anywhere in an array — start, end, middle, and anywhere else in-between.
The splice() method adds, removes and replaces elements in an array. It is commonly used for array management. This method does not create a new array but updates the one that called it.
Let’s see splice() in action. We’re going to take an array of weekdays, and add a «wednesday» element between «tuesday» and «thursday»:
const weekdays = ['monday', 'tuesday', 'thursday', 'friday'] const deletedArray = weekdays.splice(2, 0, 'wednesday'); console.log(weekdays); console.log(deletedArray);
The above code logs this to the console:
[ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday' ] []
Let’s break down the above code. We wanted to add «wednesday» in the weekdays array at the 2nd position. No element needs to be deleted here. The code weekdays.splice(2, 0, «wednesday») is read as at the second position, do not remove any element and add «wednesday».
Here’s the general syntax for using splice() :
let removedItems = array.splice(start[, deleteCount[, item1[, item2[, . ]]]])
- start — The index at which to begin modifying the array.
- deleteCount — The optional number of items in the array to remove from start . If omitted, then all the items after start will be deleted.
- item1, item2, . — The optional items to append to the array from start . If omitted, it will only remove elements from the array.
Let’s see another example of slice() where we add and delete to the array at the same time. We’ll be adding «wednesday» in the second position, however we’ll also remove erroneous weekend values there:
const weekdays = ['monday', 'tuesday', 'saturday', 'sunday', 'thursday', 'friday'] const deletedArray = array.splice(2, 2, 'wednesday'); console.log(weekdays); console.log(deletedArray);
The above code will print:
[ 'monday', 'tuesday', 'wednesday', 'thursday', 'friday' ] [ 'saturday', 'sunday' ]
In the above example, array.splice(2, 2, ‘wednesday’) removes two elements from the second position (start) and adds «wednesday» there. That right there is the power of slice() !
Conclusion
In this article, we looked at many ways in JavaScript we can add elements to an array. We can add them to the beginning with unshift() . We can add them to the end using their index, the pop() method and the concat() method. We get even more control of where we place them with the splice() method.
Array.prototype.push()
The push() method adds the specified elements to the end of an array and returns the new length of the array.
Try it
Syntax
push() push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN)
Parameters
The element(s) to add to the end of the array.
Return value
The new length property of the object upon which the method was called.
Description
The push() method appends values to an array.
Array.prototype.unshift() has similar behavior to push() , but applied to the start of an array.
The push() method is a mutating method. It changes the length and the content of this . In case you want the value of this to be the same, but return a new array with elements appended to the end, you can use arr.concat([element0, element1, /* . ,*/ elementN]) instead. Notice that the elements are wrapped in an extra array — otherwise, if the element is an array itself, it would be spread instead of pushed as a single element due to the behavior of concat() .
The push() method is generic. It only expects the this value to have a length property and integer-keyed properties. Although strings are also array-like, this method is not suitable to be applied on them, as strings are immutable.
Examples
Adding elements to an array
The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array.
const sports = ["soccer", "baseball"]; const total = sports.push("football", "swimming"); console.log(sports); // ['soccer', 'baseball', 'football', 'swimming'] console.log(total); // 4
Merging two arrays
This example uses spread syntax to push all elements from a second array into the first one.
const vegetables = ["parsnip", "potato"]; const moreVegs = ["celery", "beetroot"]; // Merge the second array into the first one vegetables.push(. moreVegs); console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
Merging two arrays can also be done with the concat() method.
Calling push() on non-array objects
The push() method reads the length property of this . It then sets each index of this starting at length with the arguments passed to push() . Finally, it sets the length to the previous length plus the number of pushed elements.
const arrayLike = length: 3, unrelated: "foo", 2: 4, >; Array.prototype.push.call(arrayLike, 1, 2); console.log(arrayLike); // const plainObj = >; // There's no length property, so the length is 0 Array.prototype.push.call(plainObj, 1, 2); console.log(plainObj); //
Using an object in an array-like fashion
As mentioned above, push is intentionally generic, and we can use that to our advantage. Array.prototype.push can work on an object just fine, as this example shows.
Note that we don’t create an array to store a collection of objects. Instead, we store the collection on the object itself and use call on Array.prototype.push to trick the method into thinking we are dealing with an array—and it just works, thanks to the way JavaScript allows us to establish the execution context in any way we want.
const obj = length: 0, addElem(elem) // obj.length is automatically incremented // every time an element is added. [].push.call(this, elem); >, >; // Let's add some empty objects just to illustrate. obj.addElem(>); obj.addElem(>); console.log(obj.length); // 2
Note that although obj is not an array, the method push successfully incremented obj ‘s length property just like if we were dealing with an actual array.
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Jul 19, 2023 by MDN contributors.
Your blueprint for a better internet.