Search code examples
javascriptif-statementforeachreturn

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. Explicitly I need the function to be able return the name value and at the same time return true or false.


Solution

  • You could use Array#some which stops iterating if a truthy value is returned inside of the callback.

    var array = [{ name: 'paul', age:20 }, { name: 'john', age:30 }, { name: 'albert', age:40 }],
        find = function(array, name) {
            return array.some(function(object) {
                return object.name === name;
            });
        };
    
    console.log(find(array, 'paul'));  // true
    console.log(find(array, 'maria')); // false