4

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.

Tukadas
  • 83
  • 2
  • 9

3 Answers3

9

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
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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');
Kevin Qian
  • 2,532
  • 1
  • 16
  • 26
  • Using the `for..of` loop with arrays isn't ideal performance-wise. Check https://stackoverflow.com/questions/13645890/javascript-for-in-vs-for-loop-performance – baeyun Mar 16 '18 at 16:54
  • @bukharim96 Yeah I did not intend to make it of high performance, simply trying to point out the problem of the original code block – Kevin Qian Mar 16 '18 at 16:57
0

Stop using the forEach method and try this instead:

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

var find = function(arr){
 var returnValue = false;
    
    for (var i = 0; i <= arr.length; i++) {
      if(arr[i].name === 'john') {
       ret = true;
       break;
      }
    }

    return returnValue;
};
find(array);
baeyun
  • 228
  • 1
  • 6