Reputation: 3317
Looking at the MDN definition of Array.prototype.find(), I was wondering if there is another javascript method to return the first object from an array based on a predicate, that also works on older browsers.
I am aware of 3rd party libraries such as _underscore and Linq.JS that do this, but curious if there is a more "native" approach.
Upvotes: 0
Views: 1407
Reputation: 2739
You can use MDN Polyfill which override this method in old browsers (Read the Tushar's comment).
if (!Array.prototype.find) {
Array.prototype.find = 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++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}
Upvotes: 5
Reputation: 957
Check this library: https://github.com/iabdelkareem/LINQ-To-JavaScript
It contains what you seek for [firstOrDefault] method for example:
var ar = [{name: "Ahmed", age: 18}, {name: "Mohamed", age:25}, {name:"Hossam", age:27}];
var firstMatch = ar.firstOrDefault(o=> o.age > 20); //Result {name: "Mohamed", age:25}
Upvotes: 0