DEV Community

Sujay Kundu
Sujay Kundu

Posted on

4 1

Javascript : Concatenating Arrays

There are 3 methods to concatenate arrays using Javascript :

Method 1: using Spread Operator (...)

Assume you have two arrays of numbers, and you want to join the two arrays :

const array1 = [1,2,3];
const array2 = [3,4,5];

// join the two arrays using spread operater '...'

const resultArray = [...array1, ...array2] 

console.log(resultArray);

//  O/P : [1,2,3,3,4,5]

Enter fullscreen mode Exit fullscreen mode

Don't forget, one can do this too:

const array1 = [1,2,3];
const array2 = [...array1, 4];

console.log(array2);

// O/P : [1,2,3,4]
Enter fullscreen mode Exit fullscreen mode

Now what if we want to concatenate three arrays ?

const array1 = [1,2,3]
const array2 = [4,5,6]
const array3 = [7,8,9]

const resultArray = [...array1, ...array2, ...array3];

console.log(resultArray);

// O/P : [1, 2, 3, 4, 5, 6, 7, 8, 9]

Enter fullscreen mode Exit fullscreen mode

Now what will happen if we try to concatenate two different arrays with different data types ?


let array1 = "letters";
let array2 =  [1, 2, 3, 4];

let resultArray = [...array1, ...array2];

console.log(resultArray );

// O/P: ["l", "e", "t", "t", "e", "r", "s", 1, 2, 3, 4]

Enter fullscreen mode Exit fullscreen mode

But why ? why not ["letters", 1, 2, 3 ,4]. This happens because if we use spread our string, it will split the word in to seperate letters. You can probably use the method 2 for that.

Lets now see on how we can do concat operation using array objects :


const array1 =  [ 
                   {
                     "id": 1,
                     "name": "John",
                    },
                    {
                      "id": 2,
                      "name": "Ron"
                    }
                 ];

const array2  = [ 
                   {
                     "id": 3,
                     "name": "Harry",
                    },
                    {
                      "id": 4,
                      "name": "Hermione"
                    }
                 ]

const resultArray = [...array1, ...array2];

console.log(resultArray);

Enter fullscreen mode Exit fullscreen mode

Method 2: Using Array.prototype.concat()

Let's use the same example, but this time using concat() method. This method does not change the existing arrays, but instead returns a new array.


const array1 = [1,2,3];
const array2 = [3,4,5];

// join the two arrays using concat()

const resultArray = array1.concat(array2);

console.log(resultArray);

// O/P : [1, 2, 3, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

But what If we want to concatenate three arrays ?

const array1 = [1,2,3];
const array2 = [4,5,6];
const array3 = [7,8,9];

const resultArray = array1.concat(array2, array3);

console.log(resultArray);

// O/P : [1,2,3,4,5,6,7,8,9]

Enter fullscreen mode Exit fullscreen mode

now let's check for concatenating arrays of two different types:



const array1 = [1,2,3,4];
const array2 = 'letters';

const resultArray = array1.concat(array2);

console.log(resultArray);

// O/P : [1, 2, 3, 4, "letters"]
Enter fullscreen mode Exit fullscreen mode

Method 3: using Array.prototype.push()

when using push, its important to remember that it won't create a new array, and change existing array data. so use this by keeping this in mind.

Using Spread and push()


const array1 = [1,2,3];
const array2 = [4,5,6];

const resultArray = array1.push(...array2);

// when you use push, it returns the LENGTH of the combined array

console.log(resultArray);  // 6

console.log(array1); // [1, 2, 3, 4, 5, 6]

console.log(array2); // [4, 5, 6]

Enter fullscreen mode Exit fullscreen mode

Using forEach and push() :


const array1 = [1,2,3];
const array2 = [4,5,6];

const resultArray = array2.forEach(item => array1.push(item));

console.log(array1); // [1,2,3,4,5,6]

Enter fullscreen mode Exit fullscreen mode
Using for and push() :

const array1 = [1,2,3];
const array2 = [4,5,6];

for(let x=0; x<array2.length; x++) { 
     array1.push(array2[x]);
} 

console.log(array1); // 1,2,3,4,5,6

Enter fullscreen mode Exit fullscreen mode

Zipper Merge ( Merging two sorted arrays )

Let's think of a scenario, where we have two arrays (both sorted) like :

const array1 = [1, 3, 5];
const array2 = [2, 4, 6];
Enter fullscreen mode Exit fullscreen mode

and the output we want is also sorted ! something like :

const resultArray = [1, 2, 3, 4, 5, 6];
Enter fullscreen mode Exit fullscreen mode

This can be solved easily using spread operator :


// function to return zipped array
function zip(array1, array2) {

      // merge the two sorted arrays 
      let result = [...array1, ...array2];  // [1, 3, 5, 2, 4, 6]

      // sort the result array again 
      return result.sort((a,b) => a-b);  // [1, 2, 3, 4, 5, 6]
}


const array1 = [1, 3, 5];
const array2 = [2, 4, 6];

const resultArray = zip(array1, array2);

console.log(resultArray); // [1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

Unique Array from Two Arrays

Now let's think of a scenario, where you have two arrays (with some elements in common ) like:


const array1 = [1, 2, 3, 4];
const array2 = [3, 4, 5, 6];

Enter fullscreen mode Exit fullscreen mode

and the output we want is a new array with unique elements only :


const resultArray = [1, 2, 3, 4, 5, 6];
Enter fullscreen mode Exit fullscreen mode

So what should we do ? We can create a unique array using spread operator and sets like this:


const array1 = [1, 2, 3, 4];
const array2 = [3, 4, 5, 6];

const mergedArray = [...array1, ...array2];

console.log(mergedArray) // [1, 2, 3, 4, 3, 4, 5, 6]

const resultArray = [...new Set(mergedArray)]; 

console.log(resultArray) // [1, 2, 3, 4, 5, 6]

Enter fullscreen mode Exit fullscreen mode

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

While many AI coding tools operate as simple command-response systems, Qodo Gen 1.0 represents the next generation: autonomous, multi-step problem-solving agents that work alongside you.

Read full post

Top comments (4)

Collapse
 
jonesey712 profile image
Jonesey712

May I ask about a zipper merge?
ie:
array1=[1,3,5];
array2=[2,4,6];

to make:
newArray=[1,2,3,4,5,6]

I've always had trouble trying to understand that. Thank you!

Collapse
 
hnicolas profile image
const array1=[1,3,5];
const array2=[2,4,6];
const newArray = array1.reduce((acc, curr, i) => [...acc, curr, array2[i]], []);
Collapse
 
jonesey712 profile image
Jonesey712

Thank you both! I don't know why it was a concept I couldn't quite get, but seeing both makes it easier to grasp!

Collapse
 
sujaykundu777 profile image
Sujay Kundu

Glad you asked ! I have added about zipper merge in the post ! :D

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post