Introduction
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:
- Start/First element
- End/Last element
- Anywhere else
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:
3
3
undefined
[ 1, 2, 3, 4 ]
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:
7
[ 1, 2, 3, 4, 5, 6, 7 ]
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);
Which prints this output:
[ 1, 2, 3, 4, 5, 6 ]
[ 1, 2, 3 ]
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:
[ 1, 2, 3, 4, 5, 6, 7, 8, 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[, ...]]]])
Where:
start
- The index at which to begin modifying the array.deleteCount
- The optional number of items in the array to remove fromstart
. If omitted, then all the items afterstart
will be deleted.item1, item2, ...
- The optional items to append to the array fromstart
. 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.