vendredi 16 mars 2018

return false or true while iterating an array of object

I would like find() function to return true when it finds 'john' and stop iterating trough array. Or return false if looking for name, let's say maria, which is not in any of our objects. What am I not understanding that I can't achieve what I need in this code? Thanks.

var array = [
    {name:'paul',age:20},
    {name:'john',age:30},
    {name:'albert',age:40}
];

var find = function(arr){
    arr.forEach(function(i){
        if(i.name === 'john'){
            console.log('found him');
            return true;
        } else {
            console.log('not there');
            return false;
        };
    });
};
find(array);

I have seen some similar questions here but I could not get or understand answer for my question.

Aucun commentaire:

Enregistrer un commentaire