Home > front end >  Can a some() function replace nested forEach()?
Can a some() function replace nested forEach()?

Time:04-30

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.

CodePudding user response:

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
  });
});

CodePudding user response:

You could replace forEach with some and get destructured values from items.

const 
    result = arrayOne.some(([, value]) =>
        arrayTwo.some(([, { min, max }]) => value > max || value < min)
    ); 
  • Related