# Merging 2-dimensional arrays in JavaScript

Let's assume that you have a pair of 2-dimensional arrays (matrices):

```javascript```let a = [
['Erik', 'Andrea', 'Paula'],
[1990,   1993,     2005],
['male', 'female', 'female']
];

let b = [
['Barcelona', 'Barcelona', 'Calella'],
['motorbike', 'car',       'car']
];
``````

Let's assume that you want to merge both of them at `[2, 1]`. You expect the following result:

```javascript```[
['Erik', 'Andrea',    'Paula',     '']
[1990,   1993,        2005,        '']
['male', 'Barcelona', 'Barcelona', 'Calella']
['',     'motorbike', 'car',       'car']
]
``````

## Creating the merge

If you want to have the same size in every row, first create an empty matrix:

```javascript```const merge = (arr1, arr2, x, y) => {

// Getting rows of both arrays
let arr1_rows = arr1.length;
let arr2_rows = arr2.length;

// Getting cols of both arrays
let arr1_cols = arr1[0].length;
let arr2_cols = arr2[0].length;

// Calculating rows and cols of the merged matrices
let merg_rows = Math.max(arr1_rows, arr2_rows, x + arr2_rows);
let merg_cols = Math.max(arr1_cols, arr2_cols, y + arr2_cols);

// Filling the new matrice with blank spaces
let merged = Array(merg_rows).fill('').map(e => Array(merg_cols).fill(''));

// Adding first array to the matrix
for(let i = 0; i < arr1_rows; i ++){

merged[i].splice(0, arr1[i].length, ...arr1[i]);

}

// Adding second array to the matrix
for(let i = x, j = 0; i < x + arr2_rows; i ++, j ++){

merged[i].splice(y, arr2[j].length, ...arr2[j]);

}

// Returning result
return merged;

}
``````

## Result

```javascript```let res = merge(a, b, 2, 1);

/*
[
['Erik', 'Andrea', 'Paula', '']
[1990, 1993, 2005, '']
['male', 'Barcelona', 'Barcelona', 'Calella']
['', 'motorbike', 'car', 'car']
]
*/
``````

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.