How to add an element to an array in javascript ?

Active March 02, 2022    /    Viewed 119    /    Comments 0    /    Edit


Examples of how to add an element to an array in javascript:

Add an element at the end of an array using push()

Let's create a simple array:

var A = [1,2,3,4];

console.log( A );

gives

[1, 2, 3, 4]

To append a new element at the end a solution is to use push(). An example, add the element 5 to the matrix A:

A.push(5);

console.log( A );

gives

[1, 2, 3, 4, 5]

var A = [1,2,3,4];
var B = [5,6];

A.push(B);

console.log( A );

gives

[1, 2, 3, 4, Array(2)]

Concatenate two arrays in javascript

To cancatenate two arrays in javascript, a solution is to use Array.prototype.concat()

var A = [1,2,3,4];
var B = [5,6];

A = A.concat(B);

console.log( A );

gives

[1, 2, 3, 4, 5, 6]

Insert a new element for a given index using splice() in javascript

To insert a new element, a solution is to use splice(index,0,'new element'):

var A = ['a','b','c','d'];

A.splice(3, 0, "Hello");

console.log( A );

gives

['a', 'b', 'c', 'Hello', 'd']

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount