Starting from aggaton's answer, this is a function that actually returns the wanted element (or null
if not found), given the array
and a callback
function that returns a truthy value for the "correct" element:
function findElement(array, callback) { var elem; return array.some(function(e) { if (callback(e)) { elem = e; return true; } }) ? elem : null; });
Just remember that this doesn't natively work on IE8-, as it doesn't support some
. A polyfill can be provided, alternatively there's always the classic for
loop:
function findElement(array, callback) { for (var i = 0; i < array.length; i++) if (callback(array[i])) return array[i]; return null; });
It's actually faster and more compact. But if you don't want to reinvent the wheel, I suggest using an utility library like underscore or lodash.