So I solved this challenge 'Finders Keepers' on Free Code Camp, but I'm dissatisfied with my solution.
The problem [link here]
asks to write a function that takes two parameters, an array and a function, and returns the first element in the array that returns true when passed to the second parameter's function.
My solution:
function find(arr, func) {
return arr.filter(function(val) {
return func(val);
})[0];
}
find([1, 2, 3, 4], function(num){ return num % 2 === 0; });
certainly works, but it iterates over all the array elements, only to return the first. That's fine if the array is only four elements long, but what if it was much longer?
Is there some way to get the callback function to break after returning x values?
答案 0 :(得分:1)
The problem basically describes Array.prototype.find()
function, so your code could be:
function find(arr, callback) {
return arr.find(callback)
}