Home > Net >  How to use the method some inside the reduce method?
How to use the method some inside the reduce method?

Time:11-24

I generate an array without taking into account the number 1 and the number that is sent as a parameter.

I used the "some" method to return the result when the number is divisible by some index. But I would like to use the functionality of the "some" method in the reduction while the array values ​​are being processed and not at the end.

let validate = (x) => [...Array(x - 2).keys()].reduce(
    (prev, curr) => (prev[curr] = curr   2, prev), [])
    .some(i => x % i === 0);

console.log(validate(7)); // returns false because 7 is not divisible by any index between 2 and 6
console.log(validate(35)); //returns true because 35 is divisible by index 5

CodePudding user response:

.reduce isn't quite the right tool here, I think. You want to check whether any values in a range match a certain condition, so the outermost iteration method should be .some. This way, the loop breaks immediately when a match is found. The array of values to check can be constructed with Array.from.

let validate = (x) => Array.from(
  { length: x - 2 },
  (_, i) => i   2
)
  .some(i => x % i === 0);

console.log(validate(7)); // returns false because 7 is not divisible by any index between 2 and 6
console.log(validate(15)); //returns true because 35 is divisible by index 5

  • Related