Open In App

JavaScript - Append Array At The Beginning Of Another Array

Last Updated : 28 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Here are the various approaches to append an array at the beginning of another array in JavaScript

Using unshift() Method - Most Common

Uses the unshift() method to add elements of a2 at the beginning of a1 using the spread operator.

JavaScript
let a1 = [ 4, 5, 6 ];
let a2 = [ 1, 2, 3 ];
a1.unshift(...a2);
console.log(a1);

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

Using concat() Method

The concat() method creates a new array without modifying the existing arrays.

JavaScript
let a1 = [ 4, 5, 6 ];
let a2 = [ 1, 2, 3 ];
let result = a2.concat(a1);
console.log(result);

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

Using Spread Operator

Creates a new array by spreading elements of a2 first, followed by a1.

JavaScript
let a1 = [ 4, 5, 6 ];
let a2 = [ 1, 2, 3 ];
let result = [...a2, ...a1 ];
console.log(result);

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

Using splice() Method

Modifies the original array in-place. It inserts elements of a2 at the beginning of a1 using splice() with 0 as the start index.

JavaScript
let a1 = [ 4, 5, 6 ];
let a2 = [ 1, 2, 3 ];
a1.splice(0, 0, ...a2);
console.log(a1);

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

Using for Loop

It iterates over a2 in reverse order, adding each element to the start of a1 using unshift().

JavaScript
let a1 = [ 4, 5, 6 ];
let a2 = [ 1, 2, 3 ];
for (let i = a2.length - 1; i >= 0; i--) {
    a1.unshift(a2[i]);
}
console.log(a1);

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

Which Approach to Use?

  • unshift() Method: Use this when you need to modify the original array directly and you want a simple and quick solution. It is efficient for small arrays but may have performance impacts for larger arrays due to frequent element shifting.
  • concat() Method: Best for creating a new array without altering the original ones. Ideal for situations where immutability and data integrity are important.
  • Spread Operator (...): Recommended for concise, readable code when creating new arrays. It’s great when you don’t want to mutate existing arrays and prefer modern JavaScript syntax.
  • splice() Method: Useful when you need to insert elements at specific positions in an array. Be cautious, as it modifies the original array.
  • for Loop: Offers flexibility and manual control over how elements are added. It’s useful when complex logic or condition checks are needed during the addition.

Next Article

Similar Reads