1

I'm trying to implement the Underscore.js function _.find. I don't understand why my code below returns undefined for:

find([1, 2, 3, 4, 5, 6], function(num) {
  return num % 2 == 0;
});

Here is my attempt at the solution:

function find(arr,callback) {
  each(arr,item=>{
    if (callback(item)) {
      return item;
    };
  });
}
function each(arr,callback) {
  if (Array.isArray(arr)) {
    for (let i = 0; i < arr.length; i++) {
      callback(arr[i]);
    };
  } else{
    for(let key in arr) {
      callback(arr[key]);
    }
  };
}
0

1 Answer 1

2
each(arr, item => {
    if (callback(item)) {
        return item;
    }
});

You're returning inside the inner function started with item => {. It doesn't short circuit the outer function. return only stops the function execution of the function you return from.

An each loop is not supposed to return anything, and an each loop is not supposed to short circuit and should run for every element in the collection. You shouldn't use each for a search function. I don't know how underscore's source does it, but a simple for loop here will allow you to return once something is found.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much Andy Ray. Very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.