Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

208
Views
Finding index of an element in a specified array

I'm in the making of a google sheets app script where I want to check if a value from one cell is in an array of values, then find what the index is so I can direct my function to that cell.

I'm at the point where I have my array in a variable called distArray, and I want to check if "id" is in that array.

Here's the code to better visualize:

function logs() {
  let app = SpreadsheetApp
  let dest = app.getActiveSpreadsheet().getSheetByName("Baza Danych");
  let lastrow = dest.getLastRow();

  let destArr = dest.getRange(2, 1, lastrow).getValues();
  let id = app.getActiveSpreadsheet().getSheetByName("Zgloszenia").getRange(6, 2).getValue();
  let position = destArr.indexOf(id);

  Logger.log(id)
  Logger.log(destArr)
  Logger.log(position)
}

And here is the output I get.

My problem is that no matter what the value of "id" is, the index is either -1 or 0 meaning the value either is not in the array or is in the first cell.

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

Try to add .flat() at the end of the line:

let destArr = dest.getRange(2, 1, lastrow).getValues();

This way:

let destArr = dest.getRange(2, 1, lastrow).getValues().flat();

Explanation:

The method getValues() gives you a 2d array [[1],[2],[3],...].

The flat() method converts a 2d array into an ordinary flat array [1,2,3,...].

After that you will able to use array.indexOf(element) to get an index of the element in the array.

about 4 years ago · Santiago Gelvez Report

0

Description

Yuri's solution is a good example if you don't want to know which element of the array contains the value your looking for. But if you need to know which row of the array contains the value the following example shows how to search a 2D array.

Script

function find() {
  try {
    let a = [['a','b'],['c','d'],['e','f'],['g','h']];
    let b = "f";
    let c = a.findIndex( d => d.indexOf(b) >= 0 );
    console.log("c = "+c);
  }
  catch(err) {
    console.log(err);
  }
}

7:51:23 AM  Notice  Execution started
7:51:24 AM  Info    c = 2
7:51:23 AM  Notice  Execution completed

Reference

  • Array.findIndex()
  • Array.indexOf()
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!