findKey() - recreating lodash library method (codecademy task) / JavaScript

3877 views javascript

I've got a problem with the codecademy task. I am to re-create the 'findKey' lodash library method. Here there are the steps of how to do it, but I got stuck, especially at point 5.

1) Add a method to our _ object called findKey. 2) Add two parameters to this method: object and predicate. We will name our predicate function parameter predicate since this is the name used in the Lodash documentation. 3) Within the method, use a for ... in loop to iterate through each key in object. 4) Within the loop, create a variable called value and set it equal to the value at the current key in object. 5) Still within the loop, create another variable called predicateReturnValue and set it equal to the result of calling predicate with value. 6) Finally, still within the loop, use an if statement to check to see if predicateReturnValue is truthy. If it is, return the current key from the method. 7) Outside of the loop, return undefined to address all cases where no truthy values were returned from predicate.

This is my code and it is crap and doesn't work:

findKey(object, predicate){
       for(let key in object){
        let value = object[key];
        let predicateReturnValue = predicate(value); 
        if (predicateReturnValue === 'true'){
          return value;
        return undefined;

I appreciate your help!

answered question

1 Answer


You need to return the key after the truty check of the call of predicate.

function findKey(object, predicate){
    for (let key in object) {
        let value = object[key];
        let predicateReturnValue = predicate(value); 
        if (predicateReturnValue) {                   // just take the value
            return key;                               // return key

posted this

Have an answer?


Please login first before posting an answer.