How to Append Array to Another in JavaScript
-
Append an Array to Another Using the
push()
Function in JavaScript -
Append an Array to Another Using the
concat()
Function in JavaScript
This tutorial will discuss how to append an array with another array using the push()
and concat()
function in JavaScript.
Append an Array to Another Using the push()
Function in JavaScript
To append an array with another, we can use the push()
function in JavaScript. The push()
function adds an array of items to another array. For example, let’s add all of its array items into another array using the push.apply()
function. See the code below.
var myArray = ['a', 'b', 'c'];
var myArray2 = ['f', 'e']
myArray.push.apply(myArray, myArray2);
console.log(myArray)
Output:
["a", "b", "c", "d", "e"]
As you can see in the output, the two items present in the myArray2
have been added to the myArray
.
Append an Array to Another Using the concat()
Function in JavaScript
You can also concatenate two arrays to make another array using the concat()
function. For example, let’s concatenating one array with another array using the concat()
function. See the code below.
var myArray = ['a', 'b', 'c'];
var myArray2 = ['d', 'e'];
var myArray = myArray.concat(myArray2);;
console.log(myArray)
Output:
["a", "b", "c", "d", "e"]
You can change the order of the items present in the myArray
by changing the order of concatenation. Note the above two functions will fail if the array is too long. In this case, you can create your own function to append the two arrays. For example, let’s create a function with the name AppendArray
using a for
loop to append an array with another array. See the code below.
function AppendArray(arr1, arr2) {
l1 = arr1.length;
l2 = arr2.length;
for (i = 0; i < l2; i++) {
arr1[l1 + i] = arr2[i];
}
return arr1;
}
var myArray = ['a', 'b', 'c'];
var myArray2 = ['d', 'e'];
var myArray = AppendArray(myArray, myArray2);;
console.log(myArray)
Output:
["a", "b", "c", "d", "e"]
In the above code, we get the elements of arr2
using their index and adding them into arr2
at the end. The loop will continue until all the elements of arr2
have been added to arr1
. The length
function is used to get the length of an array.
Related Article - JavaScript Array
- How to Check if Array Contains Value in JavaScript
- How to Create Array of Specific Length in JavaScript
- How to Convert Array to String in JavaScript
- How to Remove First Element From an Array in JavaScript
- How to Search Objects From an Array in JavaScript
- How to Convert Arguments to an Array in JavaScript