Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  34] [ 5]  / answers: 1 / hits: 10641  / 4 Years ago, mon, february 17, 2020, 12:00:00

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



More From » typescript

 Answers
0

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





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

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

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




[#4721] Thursday, February 13, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
taylert

Total Points: 627
Total Questions: 91
Total Answers: 108

Location: Mayotte
Member since Mon, Sep 12, 2022
2 Years ago
taylert questions
Tue, Jul 28, 20, 00:00, 4 Years ago
Tue, Dec 10, 19, 00:00, 5 Years ago
Fri, Sep 13, 19, 00:00, 5 Years ago
Tue, Jan 22, 19, 00:00, 5 Years ago
;