0

I'm using range.getValues() to load an array in Google Apps Script. I want to loop through the array and do something if the array includes the value I'm looking for.

if (array.include("abc")){*doSomething*}

The problem is when I use this method, the array contain another arrays, so array.include() doesn't work. I can use a workaround like this:

for (var i = 0; i<=array.length; i++){ 
  if (array[i] == "abc"){*doSomething*}

I wonder are there a better way to do it? I tried to use array.indexOf() but it returns -1 for 0th value, which is weird

2 Answers 2

1
function find() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet1');
  const haystack=sh.getDataRange().getValues();
  const needle="44";
  let found = false;
  haystack.forEach(r=>{
    r.forEach(c=>{
      if(c==needle) {
        found=true;
      }
    })
  });
  if(found) {
    SpreadsheetApp.getUi().alert('Needle was found in haystack');
  }
}

or

function find() {
  const ss=SpreadsheetApp.getActive();
  const sh=ss.getSheetByName('Sheet1');
  const haystack=sh.getDataRange().getValues();
  const needle="44";
  let found = false;
  haystack.forEach(r=>{
    if(~r.indexOf(needle)) {
      found=true;
    }
  });
  if(found) {
    SpreadsheetApp.getUi().alert('Needle was found in haystack');
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Recommendation:

Alternatively, you can also try this way:

function arrayCheck(){
  var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  var arr = ss.getDataRange().getValues(); //Get all values from sheet
  Logger.log(arr);
  arr.forEach(function(res) {
    if(res == 'abc'){
      Logger.log("Found a match");
      //do something
    }else{
      Logger.log(res+" does not match abc");
    }
  });
}

Here's a sample sheet where I've got all the array values from:

enter image description here

Here's the result:

enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.