Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.prototype.find to search an Object in an Array

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;
}
like image 936
Enrikisimo Lopez Ramos Avatar asked Nov 30 '15 11:11

Enrikisimo Lopez Ramos


People also ask

How do you search for an item in an array?

Use filter if you want to find all items in an array that meet a specific condition. Use find if you want to check if that at least one item meets a specific condition. Use includes if you want to check if an array contains a particular value. Use indexOf if you want to find the index of a particular item in an array.

How do you find the index of an object in an array?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.


1 Answers

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);
    
like image 110
Bergi Avatar answered Oct 12 '22 19:10

Bergi