I am attempting to evenly and alternately merge multiple arrays in JavaScript/Google Apps Script. I have about 5 or 6 arrays that I need to merge. I have tried two different methods, but unfortunately, neither has worked for me. I don't have much experience with JavaScript, but I have managed to write some code up to this point. However, I am struggling to merge the arrays properly as most examples I've found online focus on merging just two arrays, which may be the root of my problem.
I have come across plenty of PHP examples that explain how to do this in a straightforward manner, making it easier for me to grasp the logic. However, the JavaScript methods I have attempted thus far have not given me the desired results. I am not sure if it's the way Apps Script formats the arrays or if they are simply not designed to handle more than two arrays at once.
Here is a glimpse of my current data structure:
var title = ["sometitle1", "sometitle2", "sometitle3"];
var link = ["somelink1", "somelink2", "somelink3"];
var date = ["somedate1", "somedate2", "somedate3"];
var data = ["somedata1", "somedata2", "somedata3"];
var all = [title, link, date, data];
var mix = [];
Note: all the variables should have the same length as the data is being fetched from a spreadsheet.
My desired output should look like this:
mix = ["sometitle1", "somelink1", "somedate1", "somedata1", "sometitle2", "somelink2", "somedate2", "somedata2", "sometitle3", "somelink3", "somedate3", "somedata3"];
I initially tried to merge them using the following Apps Script code:
return ContentService.createTextOutput(title + link + data + date)
, but it did not merge them the way I intended.
Then, I experimented with a loop merge method that I found on Stack Overflow:
for (var i = 0; all.length !== 0; i++) {
var j = 0;
while (j < all.length) {
if (i >= all[j].length) {
all.splice(j, 1);
} else {
mix.push(all[j][i]);
j += 1;
}
}
}
Unfortunately, this method resulted in the letters being merged with commas:
mix = [s, o, m, e, t, i, t, l, e, 1, s, o, m, e, t, i, t, l, e, 2, s, o, m, e, t, i, t, l, e, 3, s, o, m, e, l, i, n, k, 1, ...]
Furthermore, the data did not alternate as intended.
The code I am currently working on can be found here (with output) & here (with output).
(Also, a silly question, but should I use title[i] + \n
or title[i] + "\n"
to add new lines?)