I am trying to figure it out how to target negative numbers in an array. I have this:
function SummPositive( array ) {
}
SummPositive( [ 1, 2, 3, 4, 5, -2, 23, -1, -13, 10,-52 ] );
This is an array with negative and positive numbers. How do I target (ignore) all negative numbers in an array, when I don't know how many negative numbers are in the array?
For example, I am trying to loop through the entire array, find the positive numbers, store them in another array, and then get the sum: (1+2+3+4+5+10+23)
.
If possible I want to do this only with native js.
Just make a condition to check if it's a positive or negative number, then define an empty array negatives
and if the number is negative push it inside negatives array if positive add it to sum
variable, check working example below.
function SummPositive( numbers ) {
var negatives = [];
var sum = 0;
for(var i = 0; i < numbers.length; i++) {
if(numbers[i] < 0) {
negatives.push(numbers[i]);
}else{
sum += numbers[i];
}
}
console.log(negatives);
return sum;
}
var sum_result = SummPositive( [ 1, 2, 3, 4, 5, -2, 23, -1, -13, 10,-52 ] );
console.log(sum_result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With