Exploring the capabilities of Google Apps Script for looping and generating output

I have two spreadsheets named rawData and processedData.

The content of rawData is as follows:

Status Title Options
Live Title1

Option1, Option2, Option3, Option4

Live Title2
Option1, Option2, Option3, Option4, Option5

Live Title3 Option1, Option2, Option3

The expected format for processedData should be:

Status Title Options
Live Title1 Option1
empty Title1 Option2
empty Title1 Option3
empty Title1 Option4
Live Title2 Option1
empty Title2 Option2
empty Title2 Option3
empty Title2 Option4
empty Title2 Option5
Live Title3 Option1
empty Title3 Option2
empty Title3 Option3

The placeholder empty indicates an empty cell in the spreadsheet.

I've attempted to use the provided code but couldn't achieve the desired output due to issues with the loops and my limited experience in this language.

function formatData() {
  // Code snippet here 
}

As a newcomer to this programming language, I apologize for posing what may seem like a basic question.

Answer №1

Have you considered this adjustment? Keep in mind that there are multiple ways to modify the script.

Method 1:

Updated script:

After making modifications, your script will look like this. Specifically, focus on updating the for loop as shown below:

for (var row = 0; row < data.length; row++) {
  status = data[row][0];
  var title = data[row][1]; // Added
//    outputArray.push([status]); // Removed
  options = data[row][2].split(", "); // Modified
  for (var element = 0; element < options.length; element++) {
    if (element == 0) { // Added and modified
      outputArray.push([status, title, options[element]]);
    } else {
      outputArray.push(["", title, options[element]]);
    }
  }
}

Method 2:

Alternatively, consider this different approach for modifying the script. Make the following adjustments when implementing this method:

Updated script:

From:
// Initialise an array that will hold the output
var outputArray = [];

// Name a variable to hold the data from each set of options
var options;

var status;

// Start looping through the data
for (var row = 0; row < data.length; row++) {

  status = data[row][0];

  outputArray.push([status]);

  // Split the options into an array: "Option1, Option2, Option3" ---> [Option1, Option2, Option3]
  options = data[row][1].split(", ");

  // Loop through the array of split options and place each of them in a new row
  for (var element = 0; element < options.length; element++) {

    outputArray.push([data[row][0], // Place the title in a new row
                      options[element]]); // Place one option in the 2nd column of the row

  } // Options loop ends here

} // Data loop ends here
To:
var outputArray = data.reduce(function(ar1, e) {
  var h1 = e.splice(0, 1)[0];
  var h2 = e.splice(0, 1)[0];
  var options = e[0].split(", ");
  return ar1.concat(options.reduce(function(ar2, f, j) {
    if (f) ar2.push(j == 0 ? [h1, h2, f] : ["", h2, f]);
    return ar2;
  }, []));
}, []);
  • The end result aligns with Method 1.

Note:

  • It appears that the header "Status, Title, Options" is missing in your script. Would you like to include it?

Reference:

If I have misinterpreted your question and provided an incorrect solution, I apologize for the confusion.

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

Do AJAX requests make Cross-site scripting attacks more significant?

Currently, I am in the process of developing a React application that utilizes a PHP (Codeigniter) backend. Despite Codeigniter not handling this issue automatically, I have taken it upon myself to delve into the matter. While I comprehend the importance ...

Having trouble saving text in a textbox?

Is there a way to store text in a text box for future use? Every time I reload the page, the text in the box disappears. I have attempted the following solution: <td align='left' bgcolor='#cfcfcf'><input type="text" name="tx ...

What is the connection between importing and using destructuring in ES6 syntax?

Bring in: import React, { Component } from 'react'; Unpacking: let z, { b } = {a: 1, b: 2, c: 3} Both of these examples seem to have similar syntax. However, in the second example, z will be undefined instead of {a: 1, b: 2, c: 3}. Does this ...

Guide on assigning a callback function in JavaScript

In this code snippet, I am initializing a new object variable and passing an object as an argument: const newObj = new customObject({ first : $('#fname').val(), last : $('#lname').val(), fn : function() { alert(this ...

Performance challenges with an AngularJS application that uses pagination

Resolving Performance Issues in Paginated AngularJS Posts Application I developed a compact application that showcases JSON data as cards using AngularJS and Twitter Bootstrap 4. The app includes pagination with approximately 100 posts per page. var ro ...

How can I ensure a header is displayed on each page by utilizing CSS or JavaScript/jQuery?

On a lengthy page with approximately 15 pages of text, I would like to insert a header at the beginning of each page when the document is printed by the user. Can this functionality be achieved using CSS or JavaScript/jQuery? ...

Looking to determine if a specific element is assigned multiple class names

Help needed! Can you tell me how to check if an element contains more than one classname using pure javascript, without using jQuery? For example: If #test has both the classnames "classA and classB", then { alert(true) } else { alert(false) } Here is ...

Angular filter is causing an error message saying "Unable to interpolate," but the filter is functioning as expected

I have implemented the filter below (which I found on StackOverflow) that works perfectly fine on one page. However, when using the same object, it throws an error as shown below: app.filter('dateFormat', function dateFormat($filter){ return f ...

The "as" property in NextJS Link does not properly reload the page when opened

I recently started using NextJS and I have a question about its router. I want to link to a page, but I would like the URL to be different. <Link href="/About/About" as="/about-page"> <a> Who We Are <im ...

Detecting Scroll on Window for Specific Element using Jquery

I need help troubleshooting my code. I am trying to activate only one item that comes from the bottom of the page, but instead all div elements are getting activated. $(window).scroll(function() { $('.parallax').each(function(e) { if($( ...

Develop a fresh class by inheriting from HTMLDivElement and expanding its prototype

My goal is to add a new method to the HTMLDivElement prototype without cluttering the HTMLDivElement itself with my custom methods. This has led me to attempt creating a new class that extends the HTMLDivElement. export class ScrollableElement extends HTML ...

Guide to sending a post request with parameters in nuxt.js

I am trying to fetch data using the fetch method in Nuxt/Axios to send a post request and retrieve specific category information: async fetch() { const res = await this.$axios.post( `https://example.com/art-admin/public/api/get_single_cat_data_an ...

The Concept of Long Polling and How it Impacts Server Function

After spending a significant amount of time working with PHP, I recently discovered the concept of long polling as an alternative to sending periodic ajax requests. I've realized that sending periodic ajax can be resource-intensive, especially when c ...

Retrieve and manipulate the HTML content of a webpage that has been loaded into a

Hey, let's say I have a main.js file with the following code: $("#mirador").load("mirador.html"); This code loads the HTML content from mirador.html into index.html <div id="mirador"></div> I'm wondering if there is a way to chan ...

What is the proper way to utilize --legacy-peer-deps or enforce in a vite build?

I encountered an issue with a package called react-typed in my project. To install it, I had to use --legacy-peer-deps. When deploying, I need to use vite build. However, when I run the command, I receive the following errors: 8:59:31 AM: npm ERR! node_mo ...

I'm not sure how I can retrieve the pollId from a ReactJS poll

In my React code, I am fetching a poll using an API. However, I am facing an issue while working on the handleChange function for making a POST API request. The information required for the request includes PollId, userId, and answer. I am able to retrieve ...

Stop the recurrence of multiple clicks by incorporating a Bootstrap modal popup confirmation

$('button[name="remove_levels"]').on('click', function (e) { var $form = $(this).closest('form'); e.preventDefault(); $('#confirm').modal({ backdrop: 'static', ...

Is it feasible to activate a function when certain Vue data elements are altered?

Looking to monitor a set of data elements for changes and then save them in localStorage. Is there an easy way to achieve this? ...

Error: Undefined object while trying to access 'injection' property

After updating to React 16.x, I encountered the following error: Uncaught TypeError: Cannot read property 'injection' of undefined at injectTapEventPlugin (injectTapEventPlugin.js:23) at eval (index.js:53) at Object.<anonymous> ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...