I'm using range.getValues()
to load an array in Google Apps Script.
var array = SpreadsheetApp.getActive().getActivesheet().getRange('E10:E30').getValues();
> array = [["val1"],["val2"],["val3"],["val4"]]
I then want to loop through a separate list to see whether its elements exist in the array, using array.prototype.includes():
if(array.includes("val4")) {doSomething;}
Using array.prototype.includes() like this does not work for two reasons: 1) since each element in array
is an array in itself and 2) because the method isn't available in Google Apps Script:
TypeError: Cannot find function includes in object
Then wanted to use array.prototype.flat() to solve 1) but it seems it isn't available in Google Apps Script either. I get the following error:
TypeError: Cannot find function flat in object
This is something I could do using brute force, but surely there's a neat way of doing it?
EDIT(2019-04-07): Please be advised. With the expected V8 upgrade (ECMAScript 2017) for App Script, the language will natively support
Array.prototype.includes
and many other modern Javascript features in the near future.The simplest solution for
array.prototype.includes
is to use the following polyfill from MDN in your apps script project. Just create a script file and paste the following code - the code/polyfill will add the function directly to the Array prototype object:For
array.prototype.flat
the MDN site also provides alternative solutions. One of which leveragesarray.prototype.reduce
andarray.prototype.concat
:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat#Alternative
Replace the
.includes()
with.indexOf()+1
(it will yield0
if the element is not present, else it will yield an integer between 1 and the length of your array). It works in Google Script.Went with
if(array.indexOf("val4") > -1) {doSomething};
as suggested in the commentsI first decided to go with array.filter():
But as noted below, the arrow functions don't work in Google Apps Script
But while looking for an answer I found this to solve 1):
Definitely better than I would have been able to come up with.