Creating arrays in Google Apps Script

As a newcomer to javascript, I am in the process of developing a script for a spreadsheet that will extract specific information from it. The first obstacle I encountered was defining an array of names within the spreadsheet. An error message reading "Missing ; before statement (line 10)" is being displayed.

function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  //var values = rows.getValues();

  var Names = sheet.getRange("A2:A7");
  var NameArr = new Array(6);
  var NameCell = Names.getCell(1, 1);
  NameArr[0] = NameCell.getValue();  // <-- Here lies the problem
  NameCell = Names.getCell(2, 1);
  NameArr[1] = NameCell.getValue();
  NameCell = Names.getCell(3, 1);
  NameArr[2] = NameCell.getValue();
  NameCell = Names.getCell(4, 1);
  NameArr[3] = NameCell.getValue();
  NameCell = Names.getCell(5, 1);
  NameArr[4] = NameCell.getValue();
  NameCell = Names.getCell(6, 1);
  NameArr[5] = NameCell.getValue();

  // ...
}

Answer №1

Check out this solution

function loadRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  
  var Names = sheet.getRange("A2:A7");
  var Name = [
    Names.getCell(1, 1).getValue(),
    Names.getCell(2, 1).getValue(),
    .....
    Names.getCell(5, 1).getValue()]

Instead of creating and then populating arrays, you can do it all in one step like this.

var arr = [1,2,3,5]

You made an error with lines like this one:

var Name[0] = Name_cell.getValue(); 

Since you have already defined Name as an array, you should skip the var, so just write

Name[0] = Name_cell.getValue();

Remember, if the issue doesn't directly involve Google services, try searching for solutions in JavaScript in general.

Answer №2

There may be an issue because you are trying to declare a variable that has already been declared:

var Name = new Array(6);
//...
var Name[0] = Name_cell.getValue();  //  <-- The problem lies here: 'var'

I believe it should be corrected like this:

var Name = new Array(6);
//...
Name[0] = Name_cell.getValue();

Please test it out and let me know if it resolves the issue! ;)

Answer №3

For those facing challenges similar to what I experienced, this could provide some assistance:

let dataSet = myform.getRange("A:AA").getValues().pop();
let firstVariable = dataSet[4];
let secondVariable = dataSet[7];

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

:onchange event triggering iteration through a function

My Vue.js application is experiencing issues with infinite post requests when a selectbox value changes. I have a table component that needs to display students from different 'tutorgroups'. Each tutorgroup, like '4M07a', has its own se ...

Having trouble retrieving an object within a function by using Array.filter in Vanilla JavaScript

I have been working on creating a search functionality using Vanilla JavaScript. While the code works fine in the Browser's web console, I am facing issues with outputting the object once it is wrapped in the function. The process involves having the ...

Proper method of encoding for converting byte arrays into strings

I have been attempting to convert a byte array into a string, and all I want is to convert the numbers in the byteArray into a string format (e.g. "12459865..."). My current approach is using the following code: fileInString = Encoding.UTF8.GetString(fil ...

vue-awesome-swiper / The button's name is synchronized, causing all other swiper elements to move in unison

<template> <swiper v-for="item in items" :key="item.id" :options="swiperOption" ref="mySwiper" @someSwiperEvent="callback"> <swiper-slide>I'm Slide 1</swiper-slide> <swiper-slide>I'm Slide 2</swiper-slid ...

A guide on styling JSON key values within HTML

I need help organizing my JSON Document on an HTML page. Here is the JavaScript code I am using: xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // Optionally, here you can update ...

Extract the country name associated with each IP address listed in the CSV file

Is there a way to extract country names from multiple IP addresses at once? I have a CSV file containing several IP addresses and I need to retrieve the corresponding country names for each of them. Can anyone suggest a method to accomplish this task effic ...

Updating data in a table upon submission of a form in Rails

In my Rails 3.2 application, I am displaying a table of results using the @jobs variable passed to the view from a SQL query. I want to add a button that will trigger a controller action when clicked. The action should perform some database operations and ...

Modifying selections within a select box generated dynamically using JQuery

Looking for help on how to delegate to a static DOM element in my current situation. I need to create a dynamic select box .userDrop when .addNew is clicked, and then have the user select an option from #secDrop, triggering a change event that calls the da ...

Issue with Chrome extension's popup not displaying

I was developing a chrome extension, but I encountered an issue where the popup does not display when clicking on the icon. After researching online, I found suggestions to change page_action to browser_action. However, even after making this adjustment, ...

What steps should be taken to incorporate a user input space similar to the one found in the Wordpress new post section

I am looking to incorporate a user input section on my website similar to the one found in WordPress for creating new posts. I would like this area to have all of the same tools available, such as adding hyperlinks, bolding text, and uploading images. Ca ...

Extract the value from an array of objects

https://i.sstatic.net/fTShc.png Having some difficulty accessing the elements of an array. In order to assign a project name to a local variable projectName, I am seeking assistance with extracting the project name from the given JSON structure. Any hel ...

The event listener for 'ended' is triggering multiple times

I am in the process of developing a music app, and my goal is to have the next song automatically play when the current one ends. However, I am facing an issue where the EventListener seems to be triggered multiple times in succession - first once, then tw ...

Issue encountered while trying to connect to MongoDB: MongooseServerSelectionError

I am encountering an issue while attempting to establish a connection from my Node.js application to MongoDB using Mongoose. Every time I try to launch the application, I encounter the following error: "Error connecting to MongoDB: MongooseServerSele ...

The data is not being successfully transmitted to the controller method through the AJAX call

In my JavaScript file, I have the following code: $(document).ready(function () { $('#add-be-submit').click(function (event) { event.preventDefault(); $.ajax({ type: 'POST', url: '/snapdragon/blog/new&apos ...

Determine the total value derived from adding two option values together

I am attempting to calculate the sum of two select options and display the result. So far, my attempts have only resulted in returning the value 1. What I am aiming for is to add the values from n_adult and n_children, and then show the total under Numbe ...

Struggling to concentrate using jQuery?

When the search icon is clicked, I want the focus to be on the input so the user can start typing right away without having to manually click on it. Although I tried using focus(), it doesn't seem to work for this particular input. $('.header__ic ...

Is there a way to automatically collapse all the collapsible elements within the accordion when closing it?

I came across a similar topic on Stack Overflow about closing all children accordions when the parent accordion is closed, which seems to address my issue. Currently, I am using Bootstrap 4 and struggling to modify the code from the other topic to ensure ...

The TypeScript error indicates that an argument of type '{}' cannot be assigned to a parameter of type 'Variable Y'

exampleDataPayload = { accountDetails: { userID: '456'; groupID: '789'; } } type DataPayloadType = { accountDetails: { userID: String; groupID: String; } } export const fetchDataFromApi = async(data ...

Efficiently Converting 72 Billion Elements from Numpy Arrays to Triangular Matrices

I have a series of large 1D numpy arrays varying in size from 150,000,000 to 600,000,000 elements. My goal is to input all these elements into the upper triangle of a numpy array measuring approximately 381K x 381K. Initially, I attempted to use np.triu_ ...

Send users from the web (using JavaScript) to the Windows Phone app, and if the app is not installed, direct them

In the following code snippet, I am using angular.js to detect the mobile platform and redirect to the native app. If the app is not installed, it will redirect to the market: $scope.isMobile = { Android: function() { return navigator.userAgent.ma ...