Two new Array methods (proposed by Rick Waldron) are in the latest ECMAScript 6 specification draft:
This blog post describes them.predicate(element, index, array)find() iterates over the array (while skipping holes) and calls predicate for each element. If predicate returns true, find() stops iterating and returns the current element (1). If the callback never returns true, find() returns undefined (2).
This method could be implemented as follows.
Array.prototype.find = function (predicate, thisValue) { var arr = Object(this); if (typeof predicate !== 'function') { throw new TypeError(); } for(var i=0; i < arr.length; i++) { if (i in arr) { // skip holes var elem = arr[i]; if (predicate.call(thisValue, elem, i, arr)) { return elem; // (1) } } } return undefined; // (2) }
> ['a', NaN, 'b'].indexOf(NaN) -1With findIndex(), you can use Object.is() [2] and will have no such problem:
> ['a', NaN, 'b'].findIndex(y => Object.is(NaN, y)) 1You can also adopt a more general approach, by creating a helper function elemIs:
> function elemIs(x) { return Object.is.bind(null, x) } > ['a', NaN, 'b'].findIndex(elemIs(NaN)) 1
Furthermore, Paul Millr’s es6-shim has backported the methods to ECMAScript 5.