Alternative to array.includes() in google apps script?

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:

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      // 1. Let O be ? ToObject(this value).
      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      function sameValueZero(x, y) {
        return x === y || (typeof x === 'number' && typeof y === 'number' && isNaN(x) && isNaN(y));
      }

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        if (sameValueZero(o[k], searchElement)) {
          return true;
        }
        // c. Increase k by 1. 
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

For array.prototype.flat the MDN site also provides alternative solutions. One of which leverages array.prototype.reduce and array.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 yield 0 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.

if(array.indexOf("val4")+1) {doSomething;}

Went with if(array.indexOf("val4") > -1) {doSomething}; as suggested in the comments


I first decided to go with array.filter():

var test = array.filter(element => element == "val4");
if(test != null) {doSomething};

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):

function flatten(arrayOfArrays){
  return [].concat.apply([], arrayOfArrays);
}

Definitely better than I would have been able to come up with.