Array.prototype.find to search for an object in an array

I use Array.prototype.find to search for an Object in an array. I would like to use an identifier to find this object. I read about the find method (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;
}
+4
source share
2 answers

You pass iddirectly as a parameter to , but internally you are expecting for an object with a property . Therefore either thisArg.find()buscarPersonathis.id

  • pass object:

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

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

    lisPerson.find(element => element.id === id);
    
+2
source

AddressBook's last_id .

,

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;   
    }
}
+1

Source: https://habr.com/ru/post/1617973/


All Articles