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.

1
  • btw, you need no semicolon after a block statement { /* ... */ }. Commented Mar 16, 2018 at 16:47

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I think this is exactly what I was looking for. works perfect for me.
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');

2 Comments

Using the for..of loop with arrays isn't ideal performance-wise. Check stackoverflow.com/questions/13645890/…
@bukharim96 Yeah I did not intend to make it of high performance, simply trying to point out the problem of the original code block
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.