0

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.

2
  • Hey, I posted an answer, but then I noticed the office-scripts tag. Not 100% sure if the JS solution I gave will work in office-scripts. I'm not familiar. If it doesn't work let me know and I'll take it down. Commented Apr 15, 2022 at 18:58
  • 1
    Hey @Chris Strickland From my little experience with OfficeScripts, it's JS powered or at least has JS built into the language most of what I have written is 1:1 with JS. Commented Apr 15, 2022 at 19:21

1 Answer 1

1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

Hey, @ChrisStrickland This worked, I am going to rephrase my question though because I guess it's two multidimensional arrays... looking at how ExcelScripts stored the row data is as an array of an array... so what I had to do was var CombinedData = NewData.map(x=>[...Data[0], ...x]); instead of var CombinedData = NewData.map(x=>[...Data, ...x]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.