Inserting element in the array(beginning, middle or end)
Arrays and objects are used in almost every javascript application. In this article we focus on how to insert an element into an array using various methods that are available to us. Eventually we will find a most efficient way :)
Inserting at the end of an array
The most common way to add an element at the end of the array is using the push
method on the array prototype.
let ages = [26, 54, 32, 4, 18, 20];
ages.push(46);
ages[ages.length] = 46;
ages = ages.concat(46);
All the above three possibilities will mutate the original array. Here are the preformance stats of above three ways of inseting element at the end of the array:
Using concat
method you can add multiple elements at once into an array.
Inserting at the beginning of an array
Inserting an element at the beginning of the array can be done using builtin method unshift
. Or can be also done using concat
method.
let ages = [26, 54, 32, 4, 18, 20];
ages.unshift(46);
ages = [46].concat(ages);
Here are the preformance stats of both the ways of inseting element at the beginning of the array:
Inserting in the middle of an array
To insert an element in the middle of an array you need to use splice method, which is the most performant way.
let ages = [26, 54, 32, 4, 18, 20];
ages.splice(3, 0, 46);
// ages → [26, 54, 32, 46, 4, 18, 20];
Last Updated on
Comments