rahul2001
rahul2001

Reputation: 1657

getting "undefined" when rewriting _.find function in Javascript

I am trying to rewrite the underscore _.find() for practice and am getting undifined when running it. Heres the code:

// _.find(list, predicate, context);

var findIt = function(list, predicate) {
    for (var i = 0; i < i.length; i++) {
        if (predicate(list[i]) == true) 
            {return i;} 
        else{return false;}
    }
}

var predicate = function (first) {
    return first % 2 == 0;
}

console.log(findIt(arr, predicate));

var arr = [1, 2, 3, 5]; 

What is going wrong here?

Upvotes: 1

Views: 264

Answers (2)

Guffa
Guffa

Reputation: 700382

You are using i.length, but i is not the list.

You should return that no match was found after the loop when you know that none of the items match, not when the first match fails.

To match what the _find method does, it should return the item, not the index of the item, and return undefined if there is no match.

You are using the variable arr before assigning the value to it.

var findIt = function(list, predicate) {
    for (var i = 0; i < list.length; i++) {
      if (predicate(list[i]) == true) {
        return list[i];
      }
    }
    return undefined;
}

var predicate = function (first) {
    return first % 2 == 0;
}

var arr = [1, 2, 3, 5];

console.log(findIt(arr, predicate));

Upvotes: 1

thefourtheye
thefourtheye

Reputation: 239493

List of problems in your code

  1. You are assigning value to arr, only after passing it to findIt function. So, it will have the default value undefined in it.

  2. In the for loop, if the first element doesn't match the expected element, then you are immediately returning false, but you should be checking all the elements before returning false.

  3. The loop must be run on the length of the list, but you are using i.length, which will not work because i is a number and it will not have length property.

Upvotes: 2

Related Questions