Check if at least two elements in an array are greater than zero - JavaScript/Typescript

Memmo :

Is there a smart way to find out if there are at least two values greater than 0 in an array and return true? And false in the opposite case?
(hypothetical and wrong example using some):

const a = [9, 1, 0];
const b = [0, 0, 0];
const c = [5, 0, 0];

const cond = (el) => el > 0 && somethingElseMaybe;

console.log(a.some(cond)); // print true
console.log(b.some(cond)); // print false
console.log(c.some(cond)); // print false


Ben :

To avoid wasted effort, you should stop the checking as soon as the condition is met. I think this meets your requirement.

const a = [9, 1, 0]
const b = [0, 0, 0]
const c = [5, 0, 0]

const cond = (arr, counter = 0) => { 
    for(let x of arr) {
        if(x > 0 && (++counter > 1)) return true
    }
    return false
}

console.log(cond(a)) // print true
console.log(cond(b)) // print false
console.log(cond(c)) // print false

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=7119&siteId=1