-6

First array:

const arr1 = [[1, 2, 3, 4], [5, 6, 7, 8]];

Second array:

const arr2 = [['some1', 'some2'], ['some3', 'some4']];

Desired array:

const finalArr = [[1, 2, 3, 4], ['some1', 'some2'], ['some3', 'some4']];

So, basically finalArr should have first index array of arr1 and the rest of arr2.

How can this be done?

storagemode11
  • 875
  • 7
  • 11
  • 6
    `const finalArr = [arr1[0], ...arr2]` this should to the trick. – Ankit Nov 15 '19 at 09:35
  • I can just talk for myself, and for me the reason was that the question lacks - what was already tried and what didn't work. – Ankit Nov 15 '19 at 09:43
  • You can read [this](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – Karmidzhanov Nov 15 '19 at 09:48

3 Answers3

4

If you do not care about destroying arr2, neither about having a deep copy of arr1[0], a simple unshift() can do that:

const arr1 = [[1, 2, 3, 4], [5, 6, 7, 8]];
const arr2 = [['some1', 'some2'], ['some3', 'some4']];

arr2.unshift(arr1[0]);
console.log(JSON.stringify(arr2));

Of course those are really some conditions which may not fit your case.

tevemadar
  • 12,389
  • 3
  • 21
  • 49
1

Use ES6 spread operator as below.

const arr1 = [[1, 2, 3, 4], [5, 6, 7, 8]];

const arr2 = [['some1', 'some2'], ['some3', 'some4']];

const finalArr = [arr1[0], ...arr2];

console.log(finalArr);

Or use concat function.

const arr1 = [[1, 2, 3, 4], [5, 6, 7, 8]];
const arr2 = [['some1', 'some2'], ['some3', 'some4']];
const finalArr = [arr1[0]].concat(arr2);

console.log(finalArr);
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42
-3
const arr1 = [[1, 2, 3, 4], [5, 6, 7, 8]];

const arr2 = [['some1', 'some2'], ['some3', 'some4']];
cont finalArr = Array();
finalArr.push(arr1[0]);
finalArr.push(arr2[0]);
finalArr.push(arr2[1]);

You can also iterate through the arrays and push them dynamically.

ameer nagvenkar
  • 381
  • 1
  • 10