6

I am using Array.prototype.find to search an Object Person in an Array. I would like use the id to find this Object. I've been reading about the method find (ES6) but I don't know why my code is wrong.

This is my code:

AddresBook.prototype.getPerson = function (id) {

    return this.lisPerson.find(buscarPersona, id);

};

function buscarPersona(element, index, array) {
    if (element.id === this.id) {
        return element;
    } else
        return false;
}
0

2 Answers 2

3

You're passing the id directly as the thisArg parameter to .find(), but inside buscarPersona you expect this to be an object with a .id property. So either

  • pass an object:

    lisPerson.find(buscarPersona, {id});
    function buscarPersona(element, index, array) {
        return element.id === this.id;
    }
    
  • use this directly:

    lisPerson.find(buscarPersona, id);
    function buscarPersona(element, index, array) {
        // works in strict mode only, make sure to use it
        return element.id === this;
    }
    
  • just pass a closure

    lisPerson.find(element => element.id === id);
    
1

A dirty solution could be added the last_id in the AddressBook's Prototype.

So your code would be the following

AddressBook.prototype.getPerson = function(id){
    this.last_id = id;
    return this.lisPerson.find(buscarPersona,this);
}
function buscarPersona(element){
    if(element.id === this.last_id){
        return element;
    }else{
        return false;   
    }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.