JavaScript - Append Array At The End Of Another Array
Last Updated :
28 Nov, 2024
Improve
Here are the different approaches to append an array at the end of another array in JavaScript
push() Method with Spread Operator - Most Used
It uses push() combined with the spread operator to append elements of a2 to a1.
let a1 = [ 1, 2, 3 ];
let a2 = [ 4, 5, 6 ];
a1.push(...a2);
console.log(a1);
Output
[ 1, 2, 3, 4, 5, 6 ]
Using concat() Method
It concatenates a1 and a2 into a new array, preserving the original arrays.
let a1 = [ 1, 2, 3 ];
let a2 = [ 4, 5, 6 ];
let result = a1.concat(a2);
console.log(result);
Output
[ 1, 2, 3, 4, 5, 6 ]
Using Spread Operator
It combines a1 and a2 by spreading their elements into a new array.
let a1 = [1, 2, 3];
let a2 = [4, 5, 6];
let result = [...a1, ...a2];
console.log(result);
Output
[ 1, 2, 3, 4, 5, 6 ]
Using for Loop
It iterates over a2 and appends each element to a1 using push().
let a1 = [1, 2, 3];
let a2 = [4, 5, 6];
for (let i = 0; i < a2.length; i++) {
a1.push(a2[i]);
}
console.log(a1);
Output
[ 1, 2, 3, 4, 5, 6 ]
Using Array.prototype.reduce()
It uses reduce() to get elements from a2 into a copy of a1.
let a1 = [1, 2, 3];
let a2 = [4, 5, 6];
let result = a2.reduce((acc, val) => {
acc.push(val);
return acc;
}, [...a1]);
console.log(result);
Output
[ 1, 2, 3, 4, 5, 6 ]
Using splice() Method
It appends elements by modifying the original array. The elements of a2 are added at the end of a1 using splice().
let a1 = [1, 2, 3];
let a2 = [4, 5, 6];
a1.splice(a1.length, 0, ...a2);
console.log(a1);
Output
[ 1, 2, 3, 4, 5, 6 ]
Using Array.from() Method
It creates a new array by joining existing ones. The elements of a1 and a2 are combined into a new array using Array.from() and the spread operator.
let a1 = [1, 2, 3];
let a2 = [4, 5, 6];
let result = Array.from([...a1, ...a2]);
console.log(result);
Output
[ 1, 2, 3, 4, 5, 6 ]
Which Approach to Use?
- push() with Spread Operator: Use it for modifying the original array quickly and is efficient for appending smaller arrays.
- concat() Method: Recommended for immutability when you want to keep the original arrays unchanged.
- Spread Operator (...): Great for modern, readable, and concise code, especially when creating a new array.
- for Loop: Suitable when you need custom logic or condition checks during appending.
- reduce() Method: A more functional approach but may be less readable for simple tasks.
- splice() Method: Use when you want to modify the original array in-place without creating a new one.
- Array.from() Method: Provides a flexible way to create a new array when working with different iterable sources.