0

A very basic question but still learning.

I have a 1D array say = [a,b,c].

and another 2D array = [[1,2,3],[4,5,6],[7,8,9]].

How do I push the array into beginning of each row of 2D array so that my array result looks like this.

[[a,1,2,3],[b,4,5,6],[c,7,8,9]].

Mask
  • 573
  • 7
  • 24

4 Answers4

3

You can iterate each item from 2D array and add 1D array value into it.

For more help please check Unshift

var test = ['a', 'b', 'c'];

var tests = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

var index = 0;
tests.map(item => { //Iterate each item from 2D araay
  if (index < test.length) { // Check if we have any item in 1D array to avoid crash
item.unshift(test[index++]); // Unshift each item so you can add value at 0 index.
  }
});

console.log(tests);
Rajan
  • 1,512
  • 2
  • 14
  • 18
2

array1 = ["a","b","c"];
array2 = [[1,2,3],[4,5,6],[7,8,9]];


for(var i = 0; i< array2.length;i++){
  array2[i].unshift(array1[i]);
}

console.log(array2);
Avinash Dalvi
  • 8,551
  • 7
  • 27
  • 53
  • just a small question is this the fastest solution as my data can grow big? – Mask Jun 10 '20 at 11:09
  • i need to know what will big data. but this will not be fastest. but using exisitng array method to do array operation always recommended. – Avinash Dalvi Jun 10 '20 at 11:10
2

You can loop over one of the array and use unshift to push value at 0 index.

var x = ['a','b','c'];
var y = [[1,2,3],[4,5,6],[7,8,9]];

y.forEach((item, index) => item.unshift(x[index]));
console.log(y);
Karan
  • 12,059
  • 3
  • 24
  • 40
2

Here a solution with .map() and the rest operator

let singleArr = ["a","b","c"];

let multiArr = [[1,2,3],[4,5,6],[7,8,9]];

let result = multiArr.map((el, i) => [singleArr[i],...el])

console.log(result);
bill.gates
  • 14,145
  • 3
  • 19
  • 47
  • This is also one of another way to do same logic. Upvoting on this. – Avinash Dalvi Jun 10 '20 at 11:16
  • I just want to tick the answer where the loop is fastest. Now I have for,foreach and map. I realize bt the document provided that for is faster than for each. – Mask Jun 10 '20 at 11:19