Skip to content
Advertisement

Can a some() function replace nested forEach()?

I need to replace two (nested) forEach loops with a some function. The purpose of the code block is to check if the [1] elements in arrayOne are within the max & min of arrayTwo.

The code currently works fine and looks like this:

    var result = false;
    arrayOne.forEach((arrayOneElement) => {
      arrayTwo.forEach((arrayTwoElement) => {
        if (arrayOneElement[1] > arrayTwoElement[1].max || arrayOneElement[1] < arrayTwoElement[1].min) {
          result = true;
        }
      });
    }); 

Let me know if it isn’t clear enough. Really appreciate your help.

Advertisement

Answer

Yes, you can use Array#some in this situation. It would be done like this

const result = arrayOne.some((arrayOneElement) => {
  return arrayTwo.some((arrayTwoElement) => {
    return arrayOneElement[1] > arrayTwoElement[1].max || arrayOneElement[1] < arrayTwoElement[1].min
  });
});
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement