Using a Google Sheets loop to retrieve an array

I'm struggling to configure this code snippet.

My task is to create a script that extracts data from table (A25:C38) and saves it into another table as a single record. I have limited experience with FOR loops and I'm fairly new to java, could you offer some guidance?

view image description here

I attempted to write some code but it's not functioning properly. Can you assist me?

function saveCost() {
//var data = fieldRangeCost.getValues()

for (var i = 26; i <= 38; i++) {
  var fieldRangeCost = ss.getDataRange("A"+[i],"B"+[i])
   console.log(fieldRangeCost)
  const fieldvaluesCost = fieldRangeCost.map(f => formws.getRange(f).getValue())
  console.log(fieldvaluesCost) 
   }

}

I tried troubleshooting the code but did not succeed

Answer №1

Your spreadsheet contains a multi-row range with data fields and a checkbox on each row.

If the checkbox is selected, you wish to transfer the data to another section of the spreadsheet.


function savecCost() {
  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var sourceSheet = ss.getSheetByName("Sheet1")
  var dataRange = sourceSheet.getRange(26,1,13,3)
  // Logger.log("DEBUG: the data range = "+dataRange.getA1Notation())
  var data = dataRange.getValues()
  

  // create a temprary array to save the speadsheet data
  var tempArray = new Array

  // iterate through each row in the range
  for (var i = 0; i<data.length; i++ ) {
    // check if checkbox is checked
    if (data[i][2] == true){
      // Logger.log("DEBUG: i="+i+ ", value = true")
      // checkbox is selected
      // add row values to the temporary Array
      tempArray.push([data[i][0],data[i][1]])
    }
    else{
      // Logger.log("DEBUG: i="+i+", value = false")
    }
  }

  // verify if there is any data in the temporary Array
  // paste the contents of the temporary array into the spreadsheet
  if (tempArray.length >=1){
    var targetSheet =  ss.getSheetByName("Sheet2")
    var targetLR = targetSheet.getLastRow()
    var row = targetLR == 0 ? 1 : targetLR
    var targetRange = targetSheet.getRange(row,1,tempArray.length,2)
    // Logger.log("DEBUG: the target range = "+targetRange.getA1Notation())
    targetRange.setValues(tempArray)
  } 
}

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

Importing information from the Document Object Model in Vue.js, focusing on the action attribute of a form

Can Vue be used to create a binding where the data item in the Vue instance is initialized from the DOM? In my specific case, I want my Vue instance to receive the action attribute of a form element. For example, this is how my HTML would look like (the ...

Ways to increase the size of an element within an array using JavaScript

I am currently working on expanding an array in JavaScript. Here is the object below const items = [ { id: 1, name: 'Alice', designs: [ { designId: 1, designName: "designA" ...

Is there a way to adjust the image dimensions when clicked and then revert it to its original size using JavaScript?

Is there a way to make an image in an HTML file change size by 50% and then toggle back to its normal size on a second click using JavaScript? I've attempted to do it similar to the onmouseover function, but it doesn't seem to be working. Any sug ...

Injecting HTML into Vue component

Currently, I am passing some parameters into a Vue component <Slider :images= "['/img/work/slide2.png', '/img/work/slide2.png', '/img/work/slide3.png']" :html="['<div>hello</div>', ' ...

Utilize form binding with Vue router's push method

I am currently developing a filtering component for a grid system. This component includes various fields where user inputs are stored in a model. When the user fills out the form and submits it, I have the following code for the submission process: method ...

Tips on customizing the appearance of JavaScript output?

I recently created a plugin for my website with JavaScript, and one of the lines of code I used was output.innerHTML = "Test"; Is it possible to apply CSS styles to this element, or is there an alternative method? ...

Using Javascript in React Native to filter an object within an array

Struggling with a seemingly trivial issue here. Despite numerous attempts, I can't seem to find a solution. Any suggestions? I currently have an array populated with objects structured like this: [ Object { "name": "name", "descrip ...

Tips for preserving scroll location on Angular components (not the window) when navigating

My current layout setup is like this: https://i.sstatic.net/hOTbe.png In essence <navbar/> <router-outlet/> The issue I'm facing is that the router-outlet has overflow: scroll, making it scrollable (just the outlet section, not the ent ...

What is the best way to extract a value from a multi-dimensional array?

I am trying to extract the value of the array element ad_id from a multidimensional array. Upon using print_r($xmls) to display the contents of this array, I see the following structure: ..... [5] => SimpleXMLElement Object ( ...

Store the input fields of the chosen table row into an array for iterative processing

I need help with extracting input fields from a specific row in a table and adding them to an array. My goal is to loop through this array later. This is how I currently approach it: let selectedTr = []; let arr = []; $('td input:checked').eac ...

There seems to be an issue with rendering or redirecting in Jade files, the routes folder, and server/app.js

//routes/meal.js var express = require('express'); var router = express.Router(); var app = express(); /* GET users listing. */ router.get('/meal', function(req, res, next) { res.render('/home/noah/Desktop/gadfit/views/meal.jad ...

What is the best way to organize and group results in PHP MongoDB?

Using PHP, I have created a cursor that holds group by result from MongoDB using the following command: $m = new MongoClient(); $db = $m->Forensic; $c= $db->mobile_data; // JavaScript function to perform $reduce = "function (obj, prev) { prev.count ...

An array filled with unique and non-repeating elements

I want to display random country flags next to each other, making sure they do not match. However, my specific case requires a unique solution for dealing with arrays: function displayRandomFlags() { var flagurls = ["ZPlo8tpmp/chi","cJBo8tpk6/sov","QyLo ...

Adding data to the second table using Objective C

I am facing an issue with my tableView implementation. I have two tables (Cell Identifier: Call and Cell Identifier: Cell2) and I'm passing two arrays of Objects, one for each table. However, when I try to display the data in my tableView, the second ...

Issue with HighCharts Series Data Points Not Being Added

I am currently facing a major challenge in dynamically changing data for highcharts based on date. To provide context for my project, it involves logging system data with timestamps. I have implemented a date and time picker to specify the start and end da ...

Using javascript to eliminate a block of HTML code

In my AngularJS project, I am using owl-carousel and attempting to reinitialize the carousel after a change in data by using $(element).data('owlCarousel').destroy(); while also removing this block: <div class="owl-wrapper"> <div class= ...

Transfer properties to the children of this component

I'm a beginner with React and facing an issue when trying to pass custom props to this.props.children. I attempted using React.cloneElement, and while I can see the prop in the console.log within the class where I created it, it seems to get lost duri ...

TypeScript Implementation of ES6 Arrow Functions

Just diving into Typescript, I'm struggling to figure out the solution. I tried researching and looked into destructuring, but still unable to make it work. import React from "react"; import { StyleSheet, Text, View } from "react-native"; const st ...

What is the best way to showcase a PDF in Django that is saved as a blob in a MySQL database?

Within my web application, users have the ability to upload a PDF file which is then stored directly in the MySQL database for security reasons. Utilizing the code snippet below, this process allows the uploaded file to be safely saved within the database ...

The visibility of HTML elements is dependent on the presence of space

Utilizing the onkeyup event in Javascript, I am capturing the text entered into a contenteditable div and transferring it to an input field. Users have the ability to apply bold or italic styles to the selected text by highlighting and clicking on the res ...