Retrieve the specific row in the spreadsheet that corresponds to a found value

I'm a beginner with Google Apps Script and I'm working on creating a script for a spreadsheet where I need to retrieve the range for a matched value. Unfortunately, there doesn't seem to be a function like .getRow() or .getRange() that can be used directly since the value is in string format. Below are the codes I have written:

function getInfo() {
var ss1 = sheet1.getSheetByName("Sheet1");
var ss2 = sheet2.getSheetByName("Rates");
var getCountry = ss1.getRange(ss1.getLastRow(), 11).getValue();
var countryRange = ss2.getRange(2, 1, ss2.getLastRow(), 1).getValues();
var getZone = 0;

for (var i = 0; i < countryRange.length; i++) {
    if (countryRange[i] == getCountry) {
        var getrow_cr = countryRange[i].getRow();    //.getRow() cannot be applied here as it's a string value
        getZone = ss2.getRange(getrow_cr + 1, 2).getValue();
    }
}
Logger.log(getZone);
}

Can anyone help me figure out how to determine the row containing the matched string so I can retrieve the cell value next to it?

Answer №1

Your variable for looping, i, starts at 0, which corresponds to Row 2 in this case. To avoid confusion, it might be helpful to use a named variable to keep track of the first row with data:

var firstRow = 2;

When you find a match, the row in the spreadsheet will be i + firstRow.

Here is the updated code snippet:

function getInfo() {
  var sheet1 = SpreadsheetApp.getActiveSpreadsheet();
  var ss1 = sheet1.getSheetByName("Sheet1");
  var ss2 = sheet1.getSheetByName("Rates");
  var getCountry = ss1.getRange(ss1.getLastRow(), 11).getValue();
  var firstRow = 2;
  var countryRange = ss2.getRange(firstRow, 1, ss2.getLastRow(), 1).getValues();
  var getZone = 0;

  for (var i = 0; i < countryRange.length; i++) {
    if (countryRange[i][0] == getCountry) {
      var getRowCr = i + firstRow;
      getZone = ss2.getRange(getRowCr, 2).getValue();
      break; // Found what we needed, so exit the loop
    }
  }
  Logger.log(getZone);
}

It's important to note that since countryRange is a two-dimensional array with one element per row, you should reference the value in row i with countryRange[i][0]. Comparing just countryRange[i] may rely on JavaScript coercing the "row" into a String object.

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

Sorting items using jQuery filter

I am working with two sortable div containers that are connected using connectWith. Both containers contain draggable items that can be moved as desired. These items have specific classes such as group1 and group2. Let's refer to the containers as con ...

Utilize PHP within an HTML form for action without causing a redirection

I am working on an HTML form that looks like this: <form id="ContactForm" name="ContactForm" method="post" action="emailinfo.php"> On the form, there is a submit button that triggers the verify() function: <a href="#" class="button1" onClick="v ...

How can I retrieve the Id from a TextField in MUI when the select property is activated?

I am struggling to retrieve the id from the mui TextFiled element when the select property is activated. However, I am always getting an undefined value. Here is the code snippet: export default ({ onChangeSelect, input, label, options, ...

Tips for excluding a value in a Vue loop

Is there a way to exclude the value "Three" from the loop in the following code snippet? <script > const routes = [ {name: 'One', value: 24}, {name: 'Two', value: 25}, {name: 'Three', value: 26}, {name: ...

Sorting data in AngularJS using the OrderBy filter in ascending

I am using ng-repeat in my code: <label ng-repeat="atp in Keywords | unique:'atp'"> {{atp}} </label> The values in atp are as follows: client animal zoo boat I want the final output to be: animal boat client zoo Thank you for ...

Adding elements within a loop using jquery

I am currently working on adding a toggle button using Javascript. I want to include three span tags inside it as well. To achieve this, I am creating a span variable and attempting to append it within a basic FOR loop that iterates 3 times. Below is the ...

What is the correct way to integrate a HTML/CSS/JS theme into a Vue project effectively?

As a newcomer, I recently acquired a bootstrap theme that comes with HTML, CSS, and JavaScript files. My goal now is to integrate this theme into Vue in order to make it fully functional. The challenge I am facing is how to successfully incorporate the the ...

Issue with the loss of scope in the Subscribe event causing the Clipboard Copy Event

Hey there, currently I am attempting to implement a text copying feature in Angular 2. I have a function that executes when a button is pressed, fetching data from the database and converting it into readable text, which is then automatically copied to the ...

Encounter a Socket.io connection error due to net::ERR_CONNECTION_REFUSED when trying to access from multiple devices

I'm having trouble with other people's computers accessing my test chatting application. When they try to connect, they encounter this error: localhost:3000/socket.io/?EIO=4&transport=polling&t=Oi2Ko0C:1 Failed to ...

Steps for dynamically expanding a textarea in Selenium WebDriver when the element path is constantly changing

I am facing a challenge with resizing a textarea that has a dynamic xpath. I am unable to use the following JavascriptExecutor commands: (JavascriptExecutor) driver.executeScript("document.getElementById('someID').setAttribute('rows', ...

When navigating within a page, Firefox shows {{ }} tags while Chrome does not in AngularJS

After experimenting with various techniques, I managed to successfully hide the content section upon initial page load. However, when navigating within the page, the tags still appear. Any suggestions on how to resolve this issue? You can view the proble ...

How can I set a condition to open a specific page in ReactJs?

Currently, I am in the process of developing a website and have successfully implemented a profile page. This profile page consists of three buttons - Settings, Favourites, and Posts. To enhance user experience, I decided to structure it as a multi-step fo ...

Steps to invoke another service (function) prior to calling the res.view() function in sails JS:

I am looking to execute a separate function, like a Service function, before Sails renders the page into HTML. Please refer to the controller code below... var MYController = { index: function(req, res, next) { req.flash("error", "Testing hello ...

Using Javascript within a PHP file to generate JSON output

Can you integrate Javascript code within a PHP file that utilizes header('Content-Type: application/json'); to produce output in JSON format? UPDATE: I'm attempting to modify the color of a CSS class when $est = 'Crest', but the J ...

How can HTML be dynamically inserted using JavaScript without utilizing an id attribute?

Is there a way to insert HTML using JavaScript without using IDs? I have tried document.getElementsByClassName("demo").innerHTML = "example";, but it didn't work. Are there any other methods to insert HTML content besides innerHTML using classes? ...

What is the method for choosing an Object that includes an Array within its constructor?

Is there a way to retrieve a specific argument in an Object constructor that is an Array and select an index within the array for a calculation (totaling all items for that customer). I have been attempting to access the price value in the Items Object an ...

Ever since transitioning to Discord.js 13, why am I suddenly encountering a bug with the messageCreate event?

I'm encountering an issue with my external js file for Events in messageCreate.js. It seems like certain functionalities are not working correctly, even though they were functioning fine with Discord.JS version 12. For instance, when I try to return ...

The fade effect on an element cannot be achieved using setTimeout

I'm trying to call a tooltip and hide it after 9 seconds, but for some reason, it's not working as expected. The issue I'm facing is that the "tooltip" only hides after it initially loads. It doesn't respond when I click on the "Touch ...

What is the best way to include an uncomplicated HTML Element alongside a touch of JavaScript?

I'm facing an issue with WordPress. Due to security concerns, I cannot use the script tag directly within WordPress, so I have uploaded it to a separate server. My query is whether I can display the content from that link as a small widget on my WordP ...

Issue with isNan() and typeof in React framework

I'm attempting to create a field in the react-bootstrap component that only accepts numeric input. I know there is a type="number" attribute that can be used, but it's currently set to password to mask the input. Initially, I tried this approach ...