JavaScript Array ‘find’ Method
By Justin Chmura on
In working on a JavaScript API at work, I made this little snippet for adding a find method to JavaScript arrays. Since latest APIs are including a forEach and a filter, a find made sense but wasn’t there which baffles me. More than anything, I’m putting this here so I can find it later. 😛
Here it is, short and sweet:
if (typeof Array.prototype.find !== 'function') {
Array.prototype.find = function (f) {
var filtered = this.filter(f);
if (filtered && !!filtered.length) return filtered[0];
return null;
};
}