Home > Software design >  How to get the index/row number using map in Google Sheets?
How to get the index/row number using map in Google Sheets?

Time:07-27

I'm trying to get the row number, as that row meets a couple of criteria, but:

  1. I'm getting an array like this: [,,2]
  2. I've tried using filter() at the end, but it doesn't work and I'm not sure how efficient that'd be, if I'm already using map going through the data to get the row:
ar = ["ABC", 25];

vs = [["CBA", 14],
      ["ABC", 25],
      ["DRT", 34]]

function f101() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('sheet name');
  const rg=sh.getRange(1,1,sh.getLastRow(),sh.getLastRow());
  const vs=rg.getValues();
  let holder=vs.map((r,i)=>{if(r[0]==ar[0] && r[1] == ar[1]){return i;}});
}

Expected Result: 1 //2nd row

This is me trying to adapt it from this answer

CodePudding user response:

Getting the row number

function f101() {
  const ar = ["ABC", 25];
  const vs = [["CBA", 14],
  ["ABC", 25],
  ["DRT", 34]]
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('sheet name');
  const rg = sh.getRange(1, 1, sh.getLastRow(),sh.getLastColumn());
  const vs = rg.getValues();
  let holder = vs.map((r, i) => { if (r[0] == ar[0] && r[1] == ar[1]) { return i   1; } });
}

CodePudding user response:

Instead of Array.prototype.map use Array.prototype.findIndex

ar = ["ABC", 25];

vs = [["CBA", 14],
      ["ABC", 25],
      ["DRT", 34]]
      
const h = vs.findIndex((r,i) => r[0] == ar[0] && r[1] == ar[1]);
console.log(h);

  • Related