Quicker Solution to Iteration in Google Apps Script with JavaScript

I've set up a for loop to extract sales data from an array (salesLog) and transfer it to a designated sheet (targetSheet) in columns. The sales data is spread across multiple columns in the array. The loop adds up the columns between columnStart and columnEnd (unit), matches them with the corresponding row in the source sheet, and places them in the correct row in the targetSheet. While this loop does the job, it's proving to be slow and potentially inefficient with larger datasets. I'm in search of a solution to expedite this loop process. Any suggestions?

var length = POlistTarget.length;

for (var i=0; i <= length; i++){
  //locate Row
  var row = POlistSource.indexOf(POlistTarget[i]);

  //identify Columns
  var columnStart = periodArr[0]+1
  var columnEnd = periodArr.length
  var unitArr = 
salesLog.getRange(row+3,columnStart,1,columnEnd).getValues().flat().filter(row=>row!="");

  //sum up units into an array
  var unit = unitArr.reduce(function(a,b){return a+b;},0);



  //execute


    targetSheet.getRange(i+4,7,1,1).setValue(unit);
   
}

Answer №1

Explanation:

  • As pointed out by Tanaike in a comment, a key improvement is to optimize the use of setValues by calling it once outside of the for loop, rather than using setValue iteratively within the loop. This approach reduces the number of calls to set the data, enhancing efficiency. For more insights, refer to best practices.

  • Another enhancement, benefiting both performance and code readability, involves utilizing forEach instead of a traditional for loop to streamline the code.

Improved Solution:

const units = [];
POlistTarget.forEach((pt,i)=>{                         
        let row =  POlistSource.indexOf(pt);
        let columnStart = periodArr[0]+1;
        let columnEnd = periodArr.length;
        let unit = salesLog.getRange(row+3,columnStart,1,columnEnd)
                   .getValues()
                   .flat()
                   .filter(r=>r!='')
                   .reduce((a,b)=>a+b);
        units.push([unit]);                     
});

targetSheet.getRange(4,7,units.length,1).setValues(units);

Additional optimizations:

Given a complete code context, consider utilizing getRange for the entire array on salesLog to eliminate the need for the repeated use of getRange inside the for loop. This strategy could potentially eliminate the need for the loop entirely.

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

Having trouble loading a CSV file into a static folder using Node.js and Express

As a newcomer to node and express, I am exploring the integration of d3 visualizations into my web page. Essentially, I have a JavaScript file that creates all the d3 elements, which I then include in my .ejs file. I am currently attempting to replicate a ...

Which kinds of data are ideal for storage within the Vuex (Flux) pattern?

Currently delving into the world of Vuex for the first time as I develop an application in Vue.js. The complexity of this project requires a singleton storage object that is shared across all components. While Vuex appears to be a suitable solution, I am s ...

Choose the Nth option in the dropdown list using programming

Currently, I have a script that dynamically populates a select box with unknown values and quantities of items. I am looking to create another script that mimics the action of selecting the Nth item in that box. Despite my research, I have been unable to ...

Trouble arises when attempting to execute a Vue method through a Vue computed property

It seems that the issue at hand is more related to general JavaScript rather than being specific to VueJS. I have a Vue Method set up to make a Firebase Call and return the requested object, which is functioning properly: methods: { getSponsor (key) { ...

Is it possible to transfer a massive number of files using node.js?

I need to asynchronously copy a large number of files, about 25000 in total. I am currently using the library found at this link: https://github.com/stephenmathieson/node-cp. Below is the code snippet I am using: for(var i = 0; i < 25000; i++ ...

Interacting between Angular controllers and services to efficiently showcase JSON information

Recently, I started working with Angular 1.5+ and I'm facing some challenges with the basics, particularly when it comes to displaying data from a JSON file on the DOM. Although I can fetch the data successfully (at least I think so, as it console lo ...

Passing the contents of a datatable as parameters to a PHP script

I am facing a challenge with my datatable that has two columns, "Name" and "Age". After populating the datatable using Ajax, I create a button for each row. The goal is to send the "Name" and "Age" fields of the clicked row to a PHP script, which will then ...

Leveraging Mermaid for angular applications

As a newcomer to Mermaid, I am attempting to integrate it into my Angular project. Placing it in my HTML has proven successful. <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.0.1/mermaid.min.js"></script> <div class="merma ...

`How can I retrieve a PHP variable using a JavaScript AJAX request?`

When sending an AJAX request, I encounter a situation where: //javascript var rq = new XMLHTTPrequest(); rq.open('POST','test.php', true); rq.send(JSONString); Within "test.php" file, the following action is taken: //php $data = "Hel ...

What is causing the high value of scannedObjects in MongoDB even though all query fields are indexed?

My query is running slow while indexing three fields on a large collection, one of which is an array. Despite using the correct index, the number of scanned objects is high, resulting in poor performance with 300K fields. The exaggerated number of scanned ...

Executing a JavaScript function when an HTML page is loaded within an OBJECT Tag

I have a situation where I am loading an HTML page inside an object tag. Since the iPad does not support iFrames, I decided to use the object tag to load external HTML pages into a container. Everything is working well so far, but now I want to be able t ...

communicating data within a JavaScript file across server and client

One of my files, parameters.js, contains the following JavaScript code: const myJSON = { parameter1: 2, parameter2: 2. } module.exports = {myJSON} In another file called server.js, I can access this data by usin ...

"Automatically insert a new row into the table if the cell loses focus and is not left

Can someone assist me with adding a table row dynamically when a cell is filled and the input focus is lost? My JavaScript skills are not strong. Here is a link to the form: JSFIDDLE <table class="table table-timesheet" ng-controller="TimesheetCtrl"> ...

What is the solution to the error message that states a bind message provides 4 parameters, while a prepared statement "" necessitates 5?

Is there a way to fix the issue where the bind message provides 4 parameters but the prepared statement "" requires 5? I've tried solutions from others who faced similar problems without success. (I've included all classes for better error unders ...

Python - Reflecting a dataset

I am working with a dataset that includes XYZ coordinate values and a scalar value for each XYZ coordinate. My goal is to mirror this data on the YZ plane and then on the XY plane. I initially achieved this by manually inputting everything into a list or ...

Is there a way to verify that all of my HTML elements have been loaded in AngularJS?

I am currently utilizing angularJS version 1.2.1 along with angular-ui-bootstrap. Within my code, I have a collection of <ng-includes> tags from angularjs and <accordion> components from angular-ui. When loading the content, I need to initiat ...

Simple CSS for creating a "red alert badge" with a number count

Looking for the best way to display the popular red notification indicator with count in a consistent manner across various browsers. It seems tricky to achieve a design that looks seamless on all platforms, as different browsers interpret paddings differe ...

Transform date format using VueJS in JavaScript

I need to convert a date format from 19 Oct 2017 to 20171019. Is there a way to do this quickly? I am using FlatPickr in VueJs. Here is the code snippet for reference: import flatPickr from 'vue-flatpickr-component'; import 'flatpickr/dist/ ...

"Trouble with JavaScript boolean values in if-else conditions - not functioning as expected

While utilizing true/false values and checking if at least one of them is true, I am encountering an issue with the if/else statement not functioning as expected. Here is the code snippet: $scope.checkValues = function (qId) { var airport = $scope.air ...

Guide on adding an additional key:value pair to a sub document in a MongoDB collection

I'm facing difficulties trying to add a new key:value pair to an existing object in a MongoDB document. I've experimented with $each, $push, and $addToSet, but it seems like those are intended for arrays. I then attempted $set, but that only upd ...