Troubleshooting Problems with IndexOf in Javascript/Google Apps Script

Although I've found similar questions about the IndexOf function, none of the answers have resolved my specific issue.

In my case, I have a large 2D array containing names and ID codes from a spreadsheet, which I read into an array named rIdr in my apps script.

To search for a name in the first array and retrieve the corresponding value from the second array, I create two one-dimensional arrays using the IndexOf function:

var keys=[]; var vals=[]; 
//build key-val lookup arrays
for (var i = 0; i < rIdr.values.length; i++){ 
  var k = rIdr.values[i][0].toString() 
  keys[i]=k
  var v = rIdr.values[i][1].toString()
  vals[i]=k
}

My search involves names obtained from a JSON object, and iterating over these names to find matches in the key and val arrays:

jsonobj.data.forEach(function(value) {
var idx = keys.indexOf(value.first_names_txt + " " + value.last_name_txt)
var id = -1;
if (idx > -1){id = vals[idx]}
Logger.log(value.first_names_txt + " " + value.last_name_txt + " " + id)
});

Despite verifying the data types and contents of the arrays, the IndexOf function consistently returns -1, even for names that should match. For example:

var test
test = keys.indexOf("Joe Bloggs")

I'm struggling to understand why IndexOf is not working in this scenario and I would appreciate any insights or alternative solutions that avoid passing or declaring large arrays as global variables.

Thank you for your assistance.

Answer №1

Project Details

After extracting data from a json file, I created a spreadsheet with the names but purposely randomized them to remove alphabetical order. Each name was then assigned a unique ID number.

https://i.sstatic.net/wGQQ1.png

The script I've shared showcases the ID numbers corresponding to the names in the original json data file. I didn't need to create key value arrays to achieve the desired outcome, nor did I verify the existence of each name in the data array.

I've kept the json data snippet concise for clarity.

Code.gs

function test_json() {
  try {
    let jdata = {
  "type" : "entrants",
  "data" : [ {
    "type" : "entrant",
    "id" : "en_tdgwjajthr",
    "first_names_txt" : "Archie",
    "last_name_txt" : "White",
    "entrytype" : "et_dv8u152j",
    "answers" : {
      "q_wg5qq6bgvsy90rh" : "Partenza Nude-Espresso RT"
    }
  }, {
.
.
.
.
  }, {
    "type" : "entrant",
    "id" : "en_8uhauoe3jo",
    "first_names_txt" : "Valentijn",
    "last_name_txt" : "Brax",
    "entrytype" : "et_dv8u152j",
    "answers" : {
      "q_wg5qq6bgvsy90rh" : "Dulwich Paragon CC"
    }
  } ],
  "has_more_bool" : false
};
    let values = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Test").getDataRange().getValues();
    jdata.data.forEach(function(value){
      let key = value.first_names_txt+" "+value.last_name_txt;
      let found = values.find( row => row[0] ===  key );
      console.log("key = "+key+" id = "+found[1]);
    });
  }
  catch(err) {
    console.log(err)
  }
}

Execution log (abbreviated)

10:29:05 AM Notice  Execution started
10:29:06 AM Info    key = Archie White id = 21
10:29:06 AM Info    key = ari panzer id = 15
10:29:06 AM Info    key = Daniel Mulcahy id = 5
10:29:06 AM Info    key = David Streule id = 12
10:29:06 AM Info    key = Dominic Bell id = 10
10:29:06 AM Info    key = Euan Davies id = 14

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

Customized style sheets created from JSON data for individual elements

One of the elements in the API requires dynamic rendering, and its style is provided as follows: "elementStyle": { "Width": "100", "Height": "100", "ThemeSize": "M", "TopMargin": "0", " ...

The datepicker in Vuetify is failing to display any dates

My date picker modal expands correctly, but the dates are not showing up. https://i.stack.imgur.com/azC1w.png The datepicker functions perfectly on the Codepen demo, displaying the dates as expected. However, when I try to implement the same code in my ap ...

Assistance with designing in JavaScript and Python

Currently, I have a setup where my external website is extracting data from an iframe within our internal company intranet using Javascript. The extraction process is successful, but now I am faced with the challenge of accessing this harvested data in ord ...

Struggling to create a <td> with AngularJS directive

I am currently working on creating a directive for a large set of repeated HTML code that involves using tables and table data cells. Although I have experience creating directives for div elements in the past, this is my first attempt at incorporating the ...

Using Jquery to insert error messages that are returned by PHP using JSON

I am attempting to utilize AJAX to submit a form. I send the form to PHP which returns error messages in Json format. Everything works fine if there are no errors. However, if there are errors, I am unable to insert the error message. I am not sure why th ...

Issue with displaying marker information on Angular Google Maps

https://i.stack.imgur.com/qUyRo.png I'm in a bit of a pickle trying to figure out how to properly display the information when clicking on a marker. I attempted to include $scope.info in the onClick function, but it still refuses to show up. Could s ...

Animating a CSS shape with the .animate method

I need help creating a dynamic graphic for my school project using css, jquery, and html. I want to make a rectangle that moves across the screen, but I'm having trouble getting it to work properly. Despite trying different variations of the animate f ...

Dominate with asyncCommand and Ajax in MVC ActionResults

I am currently diving into front-end development and working on a project that involves fixing bugs. Right now, I am utilizing Knockout/MVC ActionResults. One of my tasks is to modify a form so that it cannot be submitted with a double click. I initially ...

Building a custom login page with axios in a react-redux application

I've encountered an issue with my login page. When I click the submit button, it does not redirect to the main Dashboard page. Check out the code below for authentication/login.js: import React, { Component } from 'react' import { Field, ...

Retrieve the image by its unique identifier while viewing a preview of the image before it is uploaded

Below is the script I am using to preview an image before it is uploaded. The HTML structure looks like this: <div> <img id="image" src="#"> </div> <input type="file" accept="image/gif, image/jpeg, image/png" onchange="readURL(th ...

Some sections of the HTML form are failing to load

I'm currently following a tutorial and applying the concepts to a Rails project I had previously started. Here's my main.js: 'use strict'; angular.module('outpostApp').config(function ($stateProvider) { $stateProvider.sta ...

ReactJS - When a child component's onClick event triggers a parent method, the scope of the parent method may not behave as anticipated

In my current setup, I have a parent component and a child component. The parent component contains a method within its class that needs to be triggered when the child component is clicked. This particular method is responsible for updating the store. Howe ...

What is the best way to transfer information between two HTML pages using PHP?

While working on updating a record, I encountered an issue trying to pass the student's ID from one page to another without displaying it in the query string. Despite attempting to use window.location and AJAX for navigation between pages, I haven&apo ...

Firebase 9 - Creating a New Document Reference

Hey everyone, I need some help converting this code to modular firebase 9: fb8: const userRef = db.collection('Users').doc(); to fb9: const userRef = doc(db, 'Users'); But when I try to do that, I keep getting this error message: Fir ...

Using Vuex's v-model to bind to a state field in an object

In my current Vuex state, I have defined a getter named configs, which looks like this: configs: { 1303401: { exampleValue: 'test' } } There is also an input where I bind the exampleValue from the Vuex store's state using v-mo ...

I'm encountering an issue in JavaScript while attempting to convert the following string into a JSON object. Can anyone assist in identifying the problem with this string?

How can I correct this string to make it a valid JavaScript JSON object? txt = '{"Categories" : [{"label":"petifores","id":"1"}, {"label":"wedding cake","id":"2"}, {"label":"shapes of cakes","id":"3"}, ...

IconButton function in ReactJS malfunctioning specifically in Firefox browser

There seems to be an issue with the click function of IconButton from Material UI not working in any version of FireFox. Below is the code snippet in question: <div className='floating-button visible-xs'> <IconButton touch={true} tool ...

Encountering Axios 404 error while trying to access the routes directory

My server.js file in Express and Node.js contains the bulk of my back-end code, except for my database config file. The file is quite lengthy, and I want to enhance maintainability by breaking it down into smaller modules that can be imported. To start t ...

Ways to retrieve information from the object received through an ajax request

When making an AJAX request: function fetchWebsiteData(wantedId) { alert(wantedId); $.ajax({ url: 'public/xml/xml_fetchwebsite.php', dataType: 'text', data: {"wantedid": wantedId}, typ ...

Clear a variable that was sent through the post method in an ajax call

Within my JavaScript file, I have the following Ajax code: // Default settings for Ajax requests $.ajaxSetup({ type: 'POST', url: path + '/relay.php' + '?curr=' + currency + "&ver=" + Ma ...