1

I have an array of objects called columns and a array of strings values called keys

I'm trying to execute some code when col.name be !== to the value of key

    columns.forEach((col, i) => {
      if (col.name !== keys[i]) {
          console.log('yes, I entered the if statement')
        //do something here
      }
    });

The loop ends but no code is being executed, except the console log inside. I want to stop at first !==, not to loop the entires values of columns How can I do it? I read the use of every, or a simple for loop but I can't do it with an array of object.

pmiranda
  • 7,602
  • 14
  • 72
  • 155

1 Answers1

3

You could take Array#some and return true to stop the iteration.

columns.some((col, i) => {
    if (col.name !== keys[i]) {
        console.log('yes, I entered the if statement')
        //do something here
        return true;
    }
});
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I tried but, maybe my code is wrong, I need to return a false because I want to stop the whole code that is inside a function. I did it with a simple `for` instead. But your answer is correct, because I ask "how to do this with a forEach" explicity, and not "how can I loop an array and stop" – pmiranda Jan 10 '20 at 14:22