What are some ways to effectively incorporate the getRange() function within a forLoop while assembling data in Google Apps Script?

EDIT: To better illustrate my difficulty, I have included an example of my data that showcases the desired outcome:

Example Data

I hope this clarifies my request.


I am seeking assistance with a complex issue: I am working on creating a summary sheet for multiple data sheets. Each data sheet (e.g., "Sheet1," "Sheet2," "Sheet3") contains an ID variable used to categorize the data within each sheet.

My goal is to iterate through all data sheets, extract and categorize the data based on the ID variable so that I have separate sections for As, Bs, and Cs from each sheet, and then merge these sections together WITH EMPTY ROWS in the summary sheet.

The progress I've made so far includes the following steps:

function main() {
  
  // SETUP.
  var app = SpreadsheetApp;
  var workbook = app.getActiveSpreadsheet();
  var activeSheet = workbook.getActiveSheet();
  
  
  // CREATE NEW SUMMARY SHEET.
  var targetSheet = workbook.getSheetByName("Summary");
  if (!targetSheet) {
    workbook.insertSheet("Summary",1);
  }
  
  
  // ARRAY OF SHEETS USED IN MY LOOP.
  var tabs = ["Sheet 1",
              "Sheet 2",
              "Sheet 3"];
  
  
  // LOOP FOR ALL SHEETS.
  for (var i = 0; i < tabs.length; i++) {
    var sheet = workbook.getSheetByName(tabs[i]);
    
    
    // GRAB THE ORIGINAL DATA.
    var originalData = sheet.getRange(5, 1, sheet.getLastRow()-5, sheet.getLastColumn()).getValues();
    
    
    // SELECT ID AND SORT BY UNIQUE IDs.
    var range = sheet.getRange(5,2,sheet.getLastRow()-5,1).getValues();
    var range = [].concat.apply([], range);
    let uniqueValues = range.filter((v, i, a) => a.indexOf(v) === i);
    
    
    // GRAB THE UNIQUE DATA PIECES IN EACH SHEET.
    for (var t = 0; t < uniqueValues.length; t++) {
      var filterText = uniqueValues[t];
      
      var newData = originalData.filter(function(item) {
        return item[1] === filterText;
      });

    // TODO: DEFINE NEXT STEPS
    // e.g., remove rows below a specific threshold.
      
    // WRITE DATA PIECES BACK TO SUMMARY SHEET.
    workbook.getSheetByName("Summary").getRange(???).setValues(newData);

    }
  }
}

The current code successfully segments the data across different data sheets. However, merging the segments poses a challenge as each iteration overwrites the previous one.

I need to devise a method to gather these segmented data pieces based on IDs and concatenate them appropriately as shown in the example data provided above.

I seem to be struggling to maintain control between loops and temporary data storage within the loops.

Answer ā„–1

Answer:

Once you have collected all the necessary data, follow these steps:

  • Iterate through each row
  • Verify the product name
  • Separate rows with the same product name into different arrays
  • Utilize setValues() to assign data for each product
  • Insert 4 empty rows after processing

Code Adjustments:

Prior to your LOOP THROUGH ALL SHEETS loop, define an array:

var dataSets = [];

Next, replace this line:

workbook.getSheetByName("Summary").getRange(???).setValues(newData);

With:

dataSets.push(newData);

After the loop, implement the data manipulation described in the first part of this answer:

// Initialize a 2D array for data storage:
var allData = [[],[],[]];
  
// Iterate over the Data sets and categorize them into allData array:
dataSets.forEach(function(dataSet) {
  dataSet.forEach(function(row) {
    if (row[1] == "Product A") {
      allData[0].push(row)
    }
    else if (row[1] == "Product B") {
      allData[1].push(row)
    }
    else if (row[1] == "Product C") {
      allData[2].push(row)
    }
  })
})

// Define the starting point for adding data to the Summary sheet:
var nextRow = 1;

// Transfer the data to the Summary sheet:
allData.forEach(function(product) {
  var noOfColumns = product[0].length;
  var noOfRows = product.length;
  workbook.getSheetByName("Summary").getRange(nextRow, 1, noOfRows, noOfColumns).setValues(product)
  nextRow += noOfRows + 4;
});

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

What is the best way to incorporate both a view and a partial view into an MVC project using JavaScript?

I am facing an issue where the order of actions being performed in my code is not as desired. I am trying to refresh the entire page after an ajax call completes a specific action, followed by loading a particular partial view. Here is my current attempt: ...

Traversing through a arranged associative array

I am working with an array containing positive integer values such as [4, 1, 75, 52, 5, 24]. My goal is to find two values in the array that have the smallest difference. In addition to this, I also need to know the original keys of those two values. To ac ...

Modifying object colors on hover using three.js

As a beginner in the world of Three.js and WebGL, my first project involves creating a model of an animal and animating it in different ways, such as having its head follow the mouse cursor. The model consists of various geometries that are combined in sep ...

Tips for dynamically coloring table cells in Spotfire based on their values

Creating Dynamic Table with HTML After successfully creating a cross table in Spotfire, I now aim to replicate the same table in HTML within a text area. I managed to add values using calculated values, but I'm stuck on how to dynamically set the bac ...

selenium sendkeys not working properly

Hey there, I'm facing an issue in my Java code while trying to use the sendKeys command with Selenium libraries. The text field I'm working with is only visible if you scroll down to view it on the screen. var element = driver.FindElement(By.Xp ...

Struggling to convert my GRAPHQL response into a JSON object that can be iterated through

Here's a little context: I'm currently working with Shopify's GraphQL API and making calls to retrieve data. The data retrieval process is successful, however, I'm facing a challenge in manipulating the data using regular JSON syntax. M ...

Issue with componentDidUpdate not triggering consistently on subsequent mounts in React

One of the functions in my codebase is responsible for switching windows (components) on a single page when a button is clicked. This particular function handles the window swapping logic: getProfileContent = () => { var html = []; if (this.st ...

The Mystery of Two Nearly Identical Functions: One function is queued using Queue.Jquery, but the effects fail to work on this particular function. What could be causing this

In short, I am currently working on my first portfolio where I am utilizing Jquery to manipulate text. My goal is to have the text fade in and out sequentially. However, when using the queue function to load another function, the text within the span tag ...

Gif stubbornly refusing to fade out even after the .fadeOut command is called

Having trouble making a gif fade out after the page loads? Here's my attempt so far: I want the overlay, which includes a white background and the gif, to gradually become transparent once the rest of the page is fully loaded. Take a look at the fol ...

Why are my functions still being called asynchronously? I must be missing something

My task involves downloading 5 files exported from our school's database and running a query based on the first export. There will be queries for the other four files, and since there are three schools, my functions need to be scalable. I have two fu ...

Is there a way to sort through nested objects with unspecified keys?

I'm looking to extract specific information from a nested object with unknown keys and create a new array with it. This data is retrieved from the CUPS API, where printer names act as keys. I want to filter based on conditions like 'printer-stat ...

What is the best way to loop through strings in a request object?

I am currently working with Express and need to scan the POST requests to create an array called openingTimes. After that, I want to generate a MongoDB document based on the user inputs. The code snippet below is functional, but I am looking for a way to ...

Using React hooks to control the throttle of useLayoutEffect

I am working on a code snippet that uses useLayoutEffect to attach an event listener for window resize events. I want to enhance it by adding a throttle of 1000ms, so that handleCanvasResize is only called once per second. Can anyone advise on the appropr ...

Clicking on the button will instantly relocate the dynamically generated content to the top of the page, thanks to Vue

Here is some dynamically generated content in the left column: <div v-for="index in total" :key="index"> <h2>Dynamic content: <span v-text="index + ' of ' + total"></span></h2> </div> There is also a butt ...

Tips for properly setting and accessing data objects in React when utilizing a Firebase database

Iā€™m encountering issues with storing and retrieving data using the useState hook in React after fetching it from a Firebase database. The issue appears to be related to not all users having all values in the playerData data packet ā€“ for example, if a p ...

The checkbox remained unchanged when I first tried to toggle it using ng-change

When I click on the checkbox input, nothing happens the first time. But when I click it again the function in ng-change() works as expected. I am confused. Am I missing something? <tr dir-paginate="product in kitchenProducts | itemsPerPage: 10"> ...

Is there a way to embed an AJAX submit form into a notification without the need for page refresh?

I have integrated the jQuery plugin toastr js () for notifications on my website. I am facing an issue where I want to include a contact form within the notification popup and submit it using AJAX. Despite having the form working fine outside of the toastr ...

Is there a tool or software available that can securely encode a text file into an HTML file without the need for loading it using AJAX?

At the moment, I'm using jQuery to load a txt file (in utf-8) via $.ajax. The txt file has some break lines, such as: line1 line2 line3 When loaded through AJAX into a variable, it appears as: line1\n\nline2\nline3 I could manuall ...

What is the best way to determine the total number of elements within this JSON data structure?

Is there a way to determine the number of elements in a JSON object using JavaScript? data = { name_data: { 35: { name: "AA", }, 47: { name: "BB", }, 48: { name: "CC", ...

What is the procedure for eliminating an event listener that does not directly invoke a function?

I have implemented an event listener in my JS file following a successful AJAX request: var pageButtonsParentElement = document.getElementById("page-buttons"); pageButtonsParentElement.addEventListener('click', event => { ...