The only time you return []
is when the condition (input[i] == 0)
matches on any element.
However, given the name of the function you only want to skip such elements.
If and only if the argument contains no other elements but 0
, return the empty array.
So the following modified code will work:
function countPositivesSumNegatives(input) {
let count = 0;
let positive = 0;
let negative = 0;
for (let i = 0; i < input.length; i++) {
if (input[i] < 0) {
negative += input[i];
}
if (input[i] > 0) {
count++;
}
}
positive = count; // Hoisted out of the loop. Unless your function contains more code, you do not need the 'count' variable at all.
let seen_nonzero = ((positive !== 0) || (negative !== 0));
// Flags whether a non-0 element is present in your input.
let a_r =
seen_nonzero
? [positive, negative]
: []
;
return a_r
}
console.log(countPositivesSumNegatives([0, 0]));
console.log(countPositivesSumNegatives([1, 2, 3, -1, -3]));
console.log(countPositivesSumNegatives([-1, -2, 0, 1, 2]));
0
solved To get empty array