datafarmer
datafarmer

Reputation: 41

How to use an element of an array as an argument of indexOf method?

I have two arrays of values. I want to use the elements of one array to be the argument of an indexOf function. But I get a -1 (meaning value not found) even when I know the value exists in the array.

I have tested this by hard coding the value in the argument of indexOf so I know in this case that my problem is with cur_data variable. When I hard code the cur_data[x] with 'xyz' the indexOf returns correct index however when I use the array value [xyz] it returns -1.

What am I doing wrong?

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]));
      }
    }
  }
}

Upvotes: 1

Views: 13944

Answers (1)

0Valt
0Valt

Reputation: 10345

2D Array of values

getValues() method returns a two-dimensional Array of values from the Range that should be accessed via the values[row][column] schema. The for loop only increments the first dimension, that is, rows, and never accesses the value via column reference. Thus, you end up passing an Array instance to the indexOf() method.

Modification

You can add a second for loop to iterate over each of the elements of the Array of values, plus modify the first loop to make it more flexible just in case you ever need to loop over 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]));    
  }
}

Comparison

indexOf() method performs search via the strict equality comparison and here is where the fun part starts. As Array instances are also Objects, meaning the same rules of comparison that apply to objects apply to them. This means that no two objects are equal (take a look at the comparison result table).

Useful links

  1. getValues() reference;
  2. indexOf() MDN reference;
  3. Equality comparisons guide;

Upvotes: 2

Related Questions