ses
ses

Reputation: 13342

Array.prototype.find() is undefined

In here

it says that this should work:

function isPrime(element, index, array) {
    var start = 2;
    while (start <= Math.sqrt(element)) {
        if (element % start++ < 1) return false;
    }
    return (element > 1);
}

console.log( [4, 5, 8, 12].find(isPrime) ); // 5

But I end up having an error:

TypeError: undefined is not a function

Why is that?

P.S.

I'm trying not to use underscorejs library since the browsers are supposed to support functions like find() already.

Upvotes: 4

Views: 16673

Answers (3)

Northnroro
Northnroro

Reputation: 545

Instead of .find(...), you also can simply use .filter(...)[0]. (For IE >= 9)

Example:

function isEven(x) {
  return x % 2 == 0;
}
console.log([3, 4, 5].find(isEven)); // 4
console.log([3, 4, 5].filter(isEven)[0]); // 4

Reference: Array.prototype.filter()

Upvotes: 4

user1980347
user1980347

Reputation:

As mentioned above, the Array.prototype.find method is an experimental feature proposed for ECMAScript 6. But if you want to use it, and you want a short polyfill that does the job, you can use this (from here):

if (!Array.prototype.find) {
  Array.prototype.find = function (callback, thisArg) {
    "use strict";
    var arr = this,
        arrLen = arr.length,
        i;
    for (i = 0; i < arrLen; i += 1) {
        if (callback.call(thisArg, arr[i], i, arr)) {
            return arr[i];
        }
    }
    return undefined;
  };
}

Upvotes: 3

lante
lante

Reputation: 7336

Use the polyfill instead, just copy-paste the following code (from this link) to enable the find method:

if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(predicate) {
      if (this == null) {
        throw new TypeError('Array.prototype.find called on null or undefined');
      }
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }
      var list = Object(this);
      var length = list.length >>> 0;
      var thisArg = arguments[1];
      var value;

      for (var i = 0; i < length; i++) {
        if (i in list) {
          value = list[i];
          if (predicate.call(thisArg, value, i, list)) {
            return value;
          }
        }
      }
      return undefined;
    }
  });
}

Upvotes: 6

Related Questions