Combining Arrays Equally and Alternating using JavaScript and Google Apps Script

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

Answer №1

Implement a for loop combined with the push() method in this manner:

function test(){
  var title = ["sometitle1","sometitle2","sometitle3"];
  var link = ["somelink1","somelink2","somelink3"];
  var date = ["somedate1","somedate2","somedate3"];
  var data = ["somedata1","somedata2","somedata3"];
  var mix = [];
  for(var n=0;n<title.length;n++){
    mix.push(title[n],link[n],date[n],data[n]);
  }
  Logger.log(JSON.stringify(mix));
}

Additionally, consider using : title[i] + "\n" to include new lines


Revise the comments below:

Ensure that your code concludes as follows:

  ...
  for(var n=0;n<titles.length;n++){
    mix.push(titles[n],links[n],descriptions[n],pubdates[n],authors[n]);
  }
  var mixString = mix.join('');// convert the array to a string without separator or choose the separator you want by changing the argument.

  //Print data and set mimetype
  return ContentService.createTextOutput(mixString)
  .setMimeType(ContentService.MimeType.RSS);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn the method to duplicate Outer HTML with the use of jQuery or Pure JavaScript

I have successfully copied the value of an input into the clipboard using the first part of the solution provided. However, I am now trying to figure out how to copy HTML content like an entire <p> tag. Currently, when attempting this, I am encounter ...

Changing the visibility of a div with an onClick event in React

Can anyone help me figure out how to toggle the display of this div on click? I've been struggling with it for a while now. Any suggestions are welcome. https://i.sstatic.net/lPZtN.png https://i.sstatic.net/8Pybg.png ...

Encountering a "Unable to use import statement outside a module" issue when trying to import react-hook-mousetrap within a Next.js project

Currently experimenting with Next.js but encountering some challenges. Recently attempted to add react-hook-mousetrap and imported it as per usual: import useMousetrap from "react-hook-mousetrap"; However, this resulted in the following error: S ...

Having difficulty populating a selection box through an ajax request in Django

I am facing an issue with creating cascading select boxes in my project (backend Django), although I believe most of the backend work has been completed. The JavaScript code I'm using is adapted from a solution found on a stackoverflow post. $(docume ...

Sending data from a child component to its parent counterpart

A component called cartComponent has a data property named cartCount which increases every time a new item is added to the cart. I want to utilize this value to update another value in the template that is not part of the component. Is it achievable? Bel ...

Sending JSON data back to the server using KeyValuePair in C#

My goal is to send my JSON list back to the POST method (EditCompanyReportField) on the C# server side. The related parameter (fieldSorted) in my method is an array object, but the values are not being passed through. I have a few question marks regarding ...

What could be causing one of my images to not appear on my Gatsby page?

Hey there, I could use some help with this issue: Recently, I created a website using Gatsby.js and deployed it to my web server (which is running NGINX on Ubuntu 20.04). The site uses Gatsby Image for querying and displaying images, and everything seems t ...

A guide to parsing a JSON Array (and not a JSON Object) on Android

I am struggling to find a way to parse a JSONArray that looks like this: [{"name":"name1","url":"url1"},{"name":"name2","url":"url2"},...] Typically, I would know how to parse JSON if it were structured differently, such as a JSON object returned instead ...

Combining arrays while deducting specific values in PHP

Let's say I have two arrays called $array1: array (size=3) 0 => array (size=5) 'id' => int 16 'project_id' => string '37' (length=2) 'description' => string 'Guitar&apos ...

Next.js and Material UI - issues with dynamic styles not functioning

I recently started using Next JS in combination with Material UI, following the example project setup provided in the documentation on Github: https://github.com/mui-org/material-ui/tree/master/examples/nextjs My main objective is to utilize Material UI&a ...

Clicking on a button within the parent element will enable you to remove the parent element multiple times with the use of VanillaJS

Within a ul element, each li contains multiple elements in the following structure: <ul> <li> <div> <p>some text </p> <button>delete</button> <div> </li> <li> ...

Access the document on the desktop and open it in a new popup window

As a novice in html coding, I'm wondering if it's possible to write window size and other properties directly into the page. Let me explain. I'm currently working on a calculator and I want to run the HTML file on my desktop. Everything wor ...

Learn the process of extracting information from a form and inserting it into a MySQL table with the help of JQuery

I'm facing an issue with my code while trying to insert input from an HTML page into MySQL. Despite creating a table in MySQL, the values from the form are not being added to the database. Can someone help me troubleshoot this problem? <form actio ...

Tips for transferring input values from a JavaScript function to a separate PHP page for storage in a database

This code snippet allows dynamic rows to be added to a table when the add button is clicked. Now, the goal is to retrieve the values entered into the text boxes and submit them to the database. <div id="addinput"> <p> <button name=" ...

What is the best ECMAScript version to select for implementing the TypeScript compiler in an Electron application?

In my Electron 5.0.6 project, I currently have es3 as the default target in my tsconfig.json file. However, I received an error message indicating that I need to upgrade to at least es6 to utilize getter/setter functionality in TypeScript. I am now contem ...

Disable automatic playback of HTML video

There is an HTML video with an image that loads initially and then disappears to play the video. I would like the image to always be visible until I click on it. Once clicked, the video should start playing. You can view the code on JSFiddle: http://jsf ...

Link the input's name to the parent's index in JavaScript

Can a relationship be established between the input element name and its parent index (div) in a way that the input name automatically changes whenever the div index changes? Imagine something like the following: <div> <input type="text" name=" ...

Having trouble formatting the date value using the XLSX Library in Javascript?

I'm having trouble separating the headers of an Excel sheet. The code I have implemented is only working for text format. Could someone please assist me? const xlsx = require('xlsx'); const workbook = xlsx.readFile('./SMALL.xlsx') ...

What is the best way to read a local text file and store its contents in a string variable within a

Within my ReactNative project, I am seeking to retrieve the content of static text files and store it in a string variable. Here is an example of how I would like to achieve this: var content = loadPlainTextFile("resources/tags.txt"); var tags = content.s ...

Differentiating between pointers and arrays in C++

I'm currently preparing for a C++ midterm, and I'm struggling to figure out what's wrong with the code below. int numbers[] = {6, 7, 2, 4, -5}; for (int i = 0; i < 5; ++i, ++numbers) cout << *numbers; I have a feeling that the ...