Home > Net >  Adding a single array of an array into an array of a multidimensional array in Excel Scripts/ Javasc
Adding a single array of an array into an array of a multidimensional array in Excel Scripts/ Javasc

Time:04-16

looking to add a single array into a multidimensional array or an array of arrays.

for example:

Data = [["A","B","C","D"]];

NewData =[[1,2,3,4],[5,6,7,8],[9,10,11,12]];

CombinedData = [];

for(i=0; i< NewData.length; i  ){
  CombinedData.push(...Data,NewData[i]);
}

However the above results in this: "CombinedData =[["A","B","C","D"],[1,2,3,4],["A","B","C","D"],[5,6,7,8],["A","B","C","D"],[9,10,11,12],["A","B","C","D"]....]"

Where what I am looking for is this: "CombinedData =[["A","B","C","D",1,2,3,4],["A","B","C","D",5,6,7,8],["A","B","C","D",9,10,11,12],]"

This is in ExcelScripts or office scripts which I know is pretty new but just looking for some sort of direction.

CodePudding user response:

You need to spread both arrays and wrap in in brackets to make a new array.

const Data = ["A","B","C","D"];
const NewData =[[1,2,3,4],[5,6,7,8],[9,10,11,12]];
var CombinedData = [];

for(i=0; i< NewData.length; i  ){
  CombinedData.push([...Data,...NewData[i]]);
}

console.log(CombinedData);

Also, you could just use map instead of the for loop:

const Data = ["A","B","C","D"];
const NewData =[[1,2,3,4],[5,6,7,8],[9,10,11,12]];
var CombinedData = NewData.map(x=>[...Data, ...x]);
console.log(CombinedData);

  • Related