Introducing a fresh counter variable inside a for loop

I'm currently working on a project with google-apps-script. My goal is to copy a row multiple times based on the number specified in a certain cell within a spreadsheet. For example, if B2 contains the number 6, I want to duplicate that row 6 times. I've been successful in replicating the row, but I'm encountering issues when trying to manipulate the data further.

Here's the initial data:

Col1   Col2       Col3
Name   6          07/14/2019

This is the desired outcome:

Col1   Col2       Col3
Name   Count 1    07/14/2019
Name   Count 2    07/14/2019
Name   Count 3    07/14/2019
Name   Count 4    07/14/2019
Name   Count 5    07/14/2019
Name   Count 6    07/14/2019

However, this is what I keep getting:

Col1   Col2       Col3
Name   Count 6    07/14/2019
Name   Count 6    07/14/2019
Name   Count 6    07/14/2019
Name   Count 6    07/14/2019
Name   Count 6    07/14/2019
Name   Count 6    07/14/2019

Below is my current code snippet:

function sample(data){

  var returnData = [];

  var col1 = data[0];
  var col2 = data[1];
  var col3 = new Date(data[2]);
  var count = 0;

  if (col2 > 1){
    var tempData = [];
    for(var i = 0; i < col2; i++){
      tempData[0] = col1;
      tempData[1] = "Count" + count;
      tempData[2] = col3;
      
      returnData.push(tempData);
    }
    count++;
  }
  return returnData;
};

I've experimented with moving the count variable around within the code, but I continue to encounter the same issue where only the last count value is being implemented. Can you point out where I may be going wrong?

Answer №1

To optimize the code, consider declaring var tempData = []; inside the for loop.

Take a look at the modified code below:

// Revised code snippet
function sample(data){

  var returnData = [];

  var col1 = data[0];
  var col2 = data[1];
  var col3 = new Date(data[2]);

  if (col2 > 1){
    
    for(var i = 1; i <= col2; i++){
      var tempData = [];
      tempData[0] = col1;
      tempData[1] = "Count " + i;
      tempData[2] = col3;
      
      returnData.push(tempData); 
    }
  }
  return returnData; 
};

function test()
{
  var returnData = sample(['Name',6,'07/14/2019']);
  for(var i = 0; i < returnData.length; i++){
    console.log(returnData[i][0] + ' ' + returnData[i][1] + ' ' + returnData[i][2])
  }
}

test();

Answer №2

Placing count++ within the for loop can help resolve the problem

Answer №3

Greetings my friend, if you already possess the variable i, what purpose does the variable count serve?


function processData(input){

  var outputData = [];

  var column1 = input[0];
  var column2 = input[1];
  var column3 = new Date(input[2]);
 

  if (column2 > 1){
    var tempData = [];
    for(let i = 1; i <= column2; i++){
      tempData[0] = column1;
      tempData[1] = "Count" + i;
      tempData[2] = column3;
      
      outputData.push(tempData);
    }
  }
  return outputData;
};

Answer №4

function generateSampleData([value1, value2, value3] = []) {
  let outputData = [];

  if (value2 > 0)
    for (var index = 1; index <= value2; index++) {
      outputData.push([value1, "Count " + index, value3]);
    }

  return outputData;
};

Answer №5

The most recent correct answer came from Bharat, who provided a solution but did not post it, so I will do so here. The resolution to this particular issue involved moving the tempData[] array within the for loop and ensuring that the count++ increment statement also remained inside the for loop after pushing the tempData.

function processData(input){

  var outputData = [];

  var category = input[0];
  var quantity = input[1];
  var dateCreated = new Date(input[2]);
  

  if (quantity > 1){
    var counter = 1;
    for(var j = 0; j < quantity; j++){
      var temporaryData = [];

      temporaryData[0] = category;
      temporaryData[1] = "Item" + counter;
      temporaryData[2] = dateCreated;
      
      outputData.push(temporaryData);
      counter++;
    }
  }
  return outputData;
};

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

Utilizing Locale to Rewrite URLs in Next.js Version 13

I've been attempting to rewrite the URL based on the locale extracted from my middleware.js, but for some reason, the URL isn't being rewritten and leads to a page-not-found error 404. Strangely though, if I manually navigate to "localhost:3000/e ...

Formulate a Generic Type using an Enum

I'm currently working on a project that involves creating a generic Type using enums. Enum export enum OverviewSections { ALL = 'all', SCORE = 'score_breakdown', PERFORMANCE = 'performance_over_time', ENGAGEMENT ...

When utilizing Express File Upload, only the initial file is uploaded during a multiple file upload process

Currently, I am developing a function that receives an array of file data obtained from user input on the front end. The files are located within req.files.fileInput, which is an array of file data objects. Within this function, I am iterating through the ...

Utilize jQuery's addClass Method when Submitting a Form Using Ajax

When the form is submitted, I would like to add a class and display a loading animation before executing the AJAX request. However, when setting async to false in the AJAX call, the AJAX request will be executed first before displaying the loading animatio ...

Using jQuery to update the parent element from within an iframe

Below is a simplified test scenario: a.html <!DOCTYPE html> <html> <body> <input type="text" id="myinput"> <iframe id="frame" src="b.html" style="width:100%;height:100%" frameBorder="0"></iframe> </bod ...

Error encountered when extending Typography variant in TypeScript with Material UI v5: "No overload matches this call"

Currently, I am in the process of setting up a base for an application using Material UI v5 and TypeScript. My goal is to enhance the Material UI theme by adding some custom properties alongside the default ones already available. The configuration in my ...

Choose up to three elements using jQuery

DEMO I'm currently working on a project where I need to select only 3 items at a time. However, all the elements are being selected instead. Can someone please provide guidance on how to achieve this? "If a user wants to select another element, th ...

Stop the context menu from popping up when the element is right-clicked

Is there a way to create a custom right-click interaction for an element on my website, <div class="myElement"></div>? I want to avoid the default context menu from popping up when the user right-clicks on this element in order to enhance the u ...

Having trouble accessing the initial two elements of an array while generating a Fibonacci series in JavaScript

Attempting to generate a Fibonacci sequence that always starts with [0, 1] using basic JS has proven challenging. The current implementation of the function does not properly return the first two items in an array when calling the corresponding n number. F ...

What is the best way to run asynchronous Mocha tests (NodeJS) sequentially?

In regards to the NodeJS Mocha testing framework, I have a question. It appears that the default behavior is to begin all tests and then handle async callbacks as they are received. For async tests, I am interested in running each test after the async po ...

`The function of clicking on a jQuery video is not functioning properly`

Whenever I attempt to click on a video using JavaScript in Firefox to display the video's ID in the console, it seems to not work. Why is this happening? $('.videoclass').click(function() { console.log(this); var id = $(this).attr("id ...

Strategies for managing null JSON responses from the server

In my front-end application, there is a function that communicates with my node.js backend server: Client function: this.geocode = (placeName) => { const url = '/api/twitter/geocode?' + 'query=' + encodeURIComponent(placeName ...

Getting the ID name from a select tag with JavaScript - A quick guide!

Can you help me retrieve the id name using JavaScript when a selection is made in a select tag? I have tried running this code, but it only alerts undefined. For instance, if I select bbb in the select tag, I should be alerted with 2 Any suggestions on ...

Are Windows Gadgets the Next Big Testing Ground?

Are there any tools or resources that offer a console, error logging, etc. for testing Windows Gadgets? I've looked around but haven't had any luck finding something like this. Appreciate any help you can provide! ...

How to access the result without using subscribe in Angular?

I am facing unexpected behavior with a method in my component: private fetchExternalStyleSheet(outerHTML: string): string[] { let externalStyleSheetText: string; let match: RegExpExecArray; const matchedHrefs = []; while (match = this.hrefReg.exe ...

What is the best way to transfer an id from JavaScript to Rails while utilizing ajax?

Is there a way to call a rail route and pass in an ID from javascript? I have recently started using rails routes within my application, even in js. The current code I am using is: # app/assets/javascript/verifying_link.js $.ajax({ url: "/verify_link/ ...

Implement a ClickEvent on a button through JavaScript, JQuery, or Bootstrap

A fun game idea I'm working on involves smurfs and toadstools. I've already made some progress, but unfortunately can't share direct images due to my reputation level. But each of the white/red and white/blue circles in the game represent ...

Guide to automating the versioning of static assets (css, js, images) in a Java-based web application

To optimize the efficiency of browser cache usage for static files, I am seeking a way to always utilize cached content unless there has been a change in the file, in which case fetching the new content is necessary. My goal is to append an md5 hash of th ...

Standardizing URLs with ExpressJS router

Seeking normalized/canonical URLs for a single page application running on an ExpressJS server. While the SPA is supported by a server-side router, templates can vary slightly for different app URLs. One particular difference is the presence of the <li ...

Querying the children of an element using jQuery

$('.Title').children(function() { var titleValue = $('.Title').text(); console.log(titleValue); }); Wondering how to access all children with the 'title' tag and log their values individually. ...