Bokchee 88 Bokchee 88 - 1 month ago 6
Javascript Question

How to target e negative number from an array, and get the sum of all positive numbers?

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 to target all negative numbers from array, when you don't know how many negative numbers are in array?

For example, I am trying
to...loop
to entire array, find the positive numbers, store them in another array, and make a sum
(1+2+3+4+5+10+23)
.

But i am noob, and i don't how to do that.
If possible to do this only with native js

Answer

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);