What is the technique for utilizing an array element as a parameter in the indexOf function?

I have encountered an issue with two arrays of values. I am trying to utilize the elements from one array as arguments for an indexOf function, but I consistently receive a -1 (indicating that the value is not found) even though I know the value exists in the array.

To troubleshoot, I manually input the value into the argument of indexOf, which confirmed that the problem lies within the cur_data variable. When I substituted cur_data[x] with 'xyz', the indexOf function returned the correct index. However, when using the actual array value [xyz], it resulted in -1.

Can you help me identify what mistake I am making?

function iterateSheets() {
  var price_data = SpreadsheetApp.openById('1Nttb7XqUlZwGtmwbcRc3QkY3f2rxx7XdsdEU3cK4K4').getSheetByName('price').getRange("A2:A353").getValues()
  var price_data2 = price_data.map(function(r) {
    return r[0];
  });
  var test = new Array(30)
  var ts = SpreadsheetApp.openById('18qFvVMVEE1k5DWUYaSezKeobcLr8I4oAmHLUpd_X99k');
  var allShts = ts.getSheets();

  for (var i = 0; i < 1; i++) //allShts.length   //need to add in code to make sure tab is one of the fcst tabs  
  {
    var cur_data = allShts[i].getRange("B8").getValues()
    if (allShts[i].getName() == "July" || allShts[i].getName() ==
      "Aug" || allShts[i].getName() == "Sept") {

      for (var x = 0; x < 1; x++) {
        Logger.log(cur_data[x])
        Logger.log(price_data2.indexOf(cur_data[x]));
      }
    }
  }
}

Answer №1

Array of Values in Two Dimensions

getValues() function retrieves a two-dimensional Array containing values from the specified Range. These values are accessed using the syntax values[row][column]. It is important to note that the initial loop only iterates over rows, neglecting columns. Consequently, an Array is inadvertently being passed to the indexOf() method.

Enhancement

To address this issue, you can introduce a nested loop to iterate through each element within the two-dimensional Array of values. Additionally, you can adapt the first loop for increased flexibility in handling multiple rows:

for (var x = 0; x < cur_data.length; x++) {
  for (var y = 0; y < cur_data[x].length; y++) {
    Logger.log(cur_data[x][y])
    Logger.log(price_data2.indexOf(cur_data[x][y]));    
  }
}

Evaluation

The indexOf() method employs strict equality comparisons during searches, leading to some interesting outcomes. As Arrays are also considered as Objects, the rules dictating object comparison extend to them as well. Essentially, no two objects are seen as equivalent (refer to the comparison result table).

Helpful Resources

  1. getValues() documentation available here;
  2. MDN reference for indexOf() accessible here;
  3. Comprehensive guide on Equality Comparisons offered here;

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

An easy way to place text along the border of an input field in a React JS application using CSS

I am struggling to figure out how to create an input box with text on the border like the one shown in the image below using CSS. I have searched extensively but have not been able to find any solutions to achieve this effect. I attempted using <input&g ...

Dealing with an Incorrect Date in JavaScript

After working on a JavaScript logic to extract date and time from certain values, I realized that my approach needed some adjustments. Initially, I parsed the DateTime and converted it to a string. Then, I split the string to retrieve the date component. ...

What is the best way to manage div visibility and sorting based on selections made in a select box?

Explaining this might get a bit confusing, but I'll do my best. In my setup, I have two select boxes and multiple divs with two classes each. Here is what I am trying to achieve: When an option is selected, only the divs with that class should be ...

Why does replacing <input> with <TextField> in Material-UI & React cause the form submission to fail?

Recently, I encountered an issue with my CRUD Todo app's form for adding tasks. Initially built with a basic HTML input and button setup, I decided to enhance the design using Material-UI components. After introducing <TextField> in place of th ...

Tips for displaying a loader image with a centered message and preventing the bootstrap modal dialogue box from closing during an AJAX response from a PHP file

I am using Bootstrap version 3.0.0. Below is the HTML code for a Bootstrap Modal: <div class="modal fade" id="newModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> < ...

Is it possible to record a video and save it directly to the server?

When using the Apache Cordova Plugin cordova-plugin-media-capture to capture a video, you may wonder how to send this video to your server and store it. An official example is provided on how to start capturing a video: // capture callback var captureSuc ...

Can subarrays be combined and retrieved as a single array?

Imagine we have a collection in mongo database structured like this: { "_id" : 1, "semester" : 1, "grades" : [ 70, 87, 90 ] } { "_id" : 2, "semester" : 1, "grades" : [ 90, 88, 92 ] } { "_id" : 3, "semester" : 1, "grades" : [ 85, 100, 90 ] } { "_id" : 4, " ...

The JavaScript script to retrieve the background color is malfunctioning

I am currently working on developing a highlighting feature for an HTML table that will dynamically change the row colors on mouseover. Below is the code snippet I have been using, but it seems to be experiencing some issues. Any assistance would be greatl ...

"Transferring a variable from the parent Layout component to its children components in Next

I am trying to figure out how to effectively pass the variable 'country' from the Layout component to its children without using state management. Basically, I want to drill it down. import { useState, useEffect } from 'react' import La ...

Issue encountered: An error occurred while attempting to define a 2-dimensional array within a switch statement in C due to the expected expression missing before the '{' token

I am currently working on a C project, but my partner and I are facing an error that we can't seem to solve. The error message indicates that there is a problem with an expected expression before '{' in the switch_statement whenever we try t ...

Create a function that takes an array as input and retrieves the element in the array that corresponds to the specified question

To solve this problem, I'm tasked with creating a function called findAnswers(answers, questions). The function should return the item in the array that corresponds to the given question. If none of the student's answers match the question, the f ...

CUnit verifies that both arrays are identical

I've been exploring the best approach to comparing arrays in CUnit for equality. The documentation I have referenced doesn't cover arrays specifically. Options I've considered: Iterating through array elements and checking them individ ...

What's the issue with reducers receiving a Function instead of an Object in Redux?

I encountered an error in my react and redux project but I am unable to figure out how to fix it. Here is the error message: The reducer received unexpected type "Function" as the previous state. It was expecting an object with keys: "posts", "sidebar" ...

When attempting to utilize OPENJSON and JOIN in SQL Server, an error of Conversion failed may occur

Creating a SQL Server stored procedure with a JSON input parameter is my current task. I've been following the documentation provided by Microsoft for guidance: OPENJSON (Transact-SQL) (refer to Example 1) Passing arrays to T-SQL procedures as JSON ...

What steps are necessary to instruct multer to store the file in a specific directory?

Having some issues with multer while trying to save an image in a specific folder. The path for the file gets uploaded to mlab successfully, but the problem arises when attempting to retrieve the image from the designated folder as it fails to save there ...

Adjusting the React Material UI TextField behavior upon a change in value while maintaining the

I have an MUI TextField component that I would like to trigger a function when it changes, while still allowing it to function as usual (without being a controlled input). <TextField onChange={(e)=>{ doSomething(e.target.value) //perhaps call ...

Adding clickable padding to a Draft.js editor can enhance the user experience and make the editing process

Is there a way to apply padding to the Draft.js Editor so that clicking on the padding area selects the Editor? If I add padding directly to the container div of the Editor, the padding displays properly but clicking on it does not enable writing in the E ...

Using array.map with Promise.all allows for concurrent execution

Currently, I am working with an array of images and attempting to apply image processing techniques using an asynchronous function. The code is functioning as expected since each image in the array contains an index field representing its position. // Res ...

Why isn't my state updating with componentDidMount()?

I am currently exploring React and working on creating a view counter for different divs. To achieve this, I require the height and scroll top height of the divs. However, after obtaining these values, I am facing issues when trying to set state with the ...

Is there a way to change the text (price) when I select an option?

<div class="single-pro-details"> <!--Customize in the CSS--> <h6>Home / Beats</h6> <h4>Unique Lil Tecca Type Beat - New Love</h4> <h2 id="price">$ ...