'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.
Solution 1:[1]
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
});
});
Solution 2:[2]
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)
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Andrew |
| Solution 2 | Nina Scholz |
