javascript tutorial - [Solved-5 Solutions] Append something to an array - javascript - java script - javascript array



Problem:

How to append an object (such as a string or number) to an array in JavaScript?

Solution 1:

Use the push() function to append to an array:

// initialize array
var arr = [
    "Hi",
    "Hello",
    "Bonjour"
];

// append new value to the array
arr.push("Hola");

console.log(arr);
click below button to copy the code. By JavaScript tutorial team

Will print

["Hi", "Hello", "Bonjour", "Hola"]
click below button to copy the code. By JavaScript tutorial team

Solution 2:

If you're only appending a single variable, then push()works just fine. If we need to append another array, use concat():

var ar1 = [1, 2, 3];
var ar2 = [4, 5, 6];

var ar3 = ar1.concat(ar2);

alert(ar1);
alert(ar2);
alert(ar3);
click below button to copy the code. By JavaScript tutorial team

Will spit out:

"1,2,3"
"4,5,6"
"1,2,3,4,5,6"
click below button to copy the code. By JavaScript tutorial team

The concat does not affect ar1 and ar2 unless reassigned, for example:

ar1 = ar1.concat(ar2);
alert(ar1);
click below button to copy the code. By JavaScript tutorial team

Will display:

"1,2,3,4,5,6"
click below button to copy the code. By JavaScript tutorial team

Solution 3:

  • WE think it's worth mentioning that push can be called with multiple arguments, which will be appended to the array in order. For example:
var arr = ['first'];
arr.push('second', 'third');
console.log(arr); // ['first', 'second', 'third']
click below button to copy the code. By JavaScript tutorial team

As a result of this we can use push.apply to append an array to another array like so:

arr.push.apply(arr, ['forth', 'fifth']);
console.log(arr); // ['first', 'second', 'third', 'forth', 'fifth']
click below button to copy the code. By JavaScript tutorial team

Annotated ES5 has more info on exactly what push and apply do. 2016 update: with spread , we don't need that apply anymore, like:

arr.push(...['fourth', 'fifth']);
console.log(arr) // ['first', 'second', 'third', 'fourth', 'fifth']
click below button to copy the code. By JavaScript tutorial team

Solution 4:

We can use push and apply function to append two arrays.

var array1 = [11, 32, 75];
var array2 = [99, 67, 34];

Array.prototype.push.apply(array1, array2);
click below button to copy the code. By JavaScript tutorial team

It will append array2 to array1. Now array1 contains [11, 32, 75, 99, 67, 34]. This code is much simpler than writing for loops to copy each and every items in the array.

Solution 5:

Use concat:

a = [1, 2, 3];
b = [3, 4, 5];
a = a.concat(b);
click below button to copy the code. By JavaScript tutorial team

a now contains all the elements, [1, 2, 3, 3, 4, 5].


Related Searches to javascript tutorial - Append something to an array