Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return false or true while iterating an array of object [duplicate]

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.

like image 974
Tukadas Avatar asked Oct 14 '25 03:10

Tukadas


2 Answers

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
like image 153
Nina Scholz Avatar answered Oct 16 '25 16:10

Nina Scholz


You are returning in the forEach(function(i) {}), which is only returning in the inside function function(i) {}, that does not help return from the outer function find(). Also, your logic with return false; seems also problematic. Simply use normal for loops would be fine.

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

var find = function(arr, name) {
  for (let i of arr) {
    if(i.name === name){
      console.log('found ' + name);
      return true;
    }
  }
  console.log(name + ' not there');
  return false;
};

find(array, 'paul');
find(array, 'maria');
like image 31
Kevin Qian Avatar answered Oct 16 '25 16:10

Kevin Qian