Add an Element to an Array in JavaScript
JavaScript arrays have 3 methods for adding an element to an array:
push()
adds to the end of the arrayunshift()
adds to the beginning of the arraysplice()
adds to the middle of the array
Below are examples of using push()
, unshift()
, and splice()
.
const arr = ['a', 'b', 'c'];
arr.push('d');
arr; // ['a', 'b', 'c', 'd']
arr.push('e', 'f');
arr; // ['a', 'b', 'c', 'd', 'e', 'f']
const arr = ['d', 'e', 'f'];
arr.unshift('c');
arr; // ['c', 'd', 'e', 'f']
arr.unshift('a', 'b');
arr; // ['a', 'b', 'c', 'd', 'e', 'f']
const arr = ['a', 'b', 'd'];
let start = 2;
let deleteCount = 0;
arr.splice(start, deleteCount, 'c');
arr; // ['a', 'b', 'c', 'd'];
These methods modify the array in place, which means they modify arr
rather than creating a copy of arr
.
You can also use the spread operator and other immutable methods that create a new array and leave arr
unmodified.
let arr = ['c'];
arr = arr.concat(['d', 'e']);
arr; // ['c', 'd', 'e']
// You can also use `concat()` to add to the beginning of
// the array, just make sure you call `concat()` on an array
// containing the elements you want to add to the beginning.
arr = ['a', 'b'].concat(arr);
arr; // ['a', 'b', 'c', 'd', 'e']
Setting an Index Directly
If you're adding an element to the end of the array, you don't necessarily have to use push()
.
You can just set the array index, and JavaScript will update the array's length for you.
let arr = ['a', 'b'];
arr[2] = 'c';
arr.length; // 3
arr; // ['a', 'b', 'c']
JavaScript does not throw an error if you set an out of bounds array index.
For example, if your array has length 3 and you set index 4
, JavaScript will just grow your array by adding a hole in the array.
const arr = ['a', 'b', 'c'];
arr[4] = 'e';
arr.length; // 5
arr; // [ 'a', 'b', 'c', <1 empty item>, 'e' ]
arr[3]; // undefined
In the above example, arr[3]
is a hole in the array.
That means arr[3] === undefined
, so be careful if you're setting out of bounds array indexes.
Avoiding Duplicates
The easiest way to avoid adding duplicates to an array is to check if the array contains the given value before adding it.
const arr = ['a', 'b', 'c'];
addWithoutDuplicates(arr, 'a'); // ['a', 'b', 'c']
addWithoutDuplicates(arr, 'd'); // ['a', 'b', 'c', 'd']
function addWithoutDuplicates(arr, el) {
if (arr.includes(el)) {
return arr;
}
arr.push(el);
return arr;
}
Using includes()
works, but can cause performance issues because includes()
scans through the entire array every time you call it.
So the below loop is O(n^2)
.
const arrWithoutDuplicates = [];
for (let i = 0; i < arr.length; ++i) {
if (arrWithoutDuplicates.includes(arr[i])) {
continue;
}
arrWithoutDuplicates.push(arr[i]);
}
Instead, we recommend using a JavaScript set to represent a collection of objects where every element should be unique.
const set = new Set(['a', 'b', 'c']);
set.add('a');
set; // Set(3) { 'a', 'b', 'c' }
set.add('d');
set; // Set(4) { 'a', 'b', 'c', 'd' }