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

杀马特。学长 韩版系。学妹 提交于 2019-12-05 17:24:54

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

You could filter the array only for positive numbers and then add all values.

var array = [ 1, 2, 3, 4, 5, -2, 23, -1, -13, 10, -52 ],
    positive = array.filter(function (a) { return a >= 0; }),
    sum = positive.reduce(function (a, b) { return a + b; });

console.log(sum);

Or use a single loop

var array = [ 1, 2, 3, 4, 5, -2, 23, -1, -13, 10, -52 ],
    sum = array.reduce(function (r, a) {
        return a > 0 ? r + a : r;
    }, 0);

console.log(sum);

Method used:

  • Array#filter:

    The filter() method creates a new array with all elements that pass the test implemented by the provided function.

  • Array#reduce:

    The reduce() method applies a function against an accumulator and each value of the array (from left-to-right) to reduce it to a single value.

I think that you mean this:

function SummPositive( array ) {
    var sum = 0;
    for(var i = 0; i < array.length; i++) {
        if(array[i] > 0) {
            sum += array[i];
        }
    }
    return sum;
}

It will sum all the positive numbers in the array and return the sum.

As a alternative you can use lastest features of ES6:

let arr = [1, 3, 1, -2];
let sum = arr.reduce(((r, x) => x > 0 ?  x + r: r), 0);
console.log(sum)

This will delete take out all negative numbers and sum the remaining values in the array.

var totalN = 0;
for(var ctr = 0; ctr < summPositive.length; ctr++){
    if(summPositive[ctr] >= 0 ){totalN += summPositive[ctr];
    }
}

You can simply filter the array to find positive

    function sumPositive(arr){
      var positiveArray = arr.filter(function(x){return x > 0});// getting positive.
      var sum = 0;  positiveArray.forEach(function(x){ sum += x;});
     return sum;
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!