Dark Mode
Enable Console
countPsumN(input)
/*
Given an array, returns a new array, where the first element is
the count of positives numbers and the second element is sum of negative numbers.
0 is neither positive nor negative.
*/
countPsumN([-15, 3, -2, 8]);
// [2, -17]
countPsumN([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -11, -12, -13, -14, -15]);
// [10, -65]
Solution by - Need4Swede
function countPsumN(input) {
// If input is empty, return an empty array
if (input == null || input.length == 0){
return [];
}
else{
// Initialize sum and counter
let negativeSum = 0;
let positiveCount = 0;
// Add every negative number to sum, and count every positive number
input.forEach(number => {
if (number < 0){
negativeSum += number
}
else if (number > 0){
positiveCount += 1;
}
});
// Return the result
return [positiveCount, negativeSum];
}
}
Try it yourself - Codewars Source