NietzscheProgrammer - 1 year ago 57

Javascript Question

I need to sum or subtract the values of an array.

For example:

`[1, 5, 10]`

`1 + 5 + 10 = 16`

And

`[1, 5, -1, 10, 5]`

`1 + 5 - 10 - 5`

`-1`

`-1`

`-1`

`-1`

Now look how it should be with 2

`-1`

`[1, 5, -1, 10, 5, -1, 5, 5]`

should be represented as:

`1 + 5 - 10 - 5 + 5 + 5`

So, everything should be sum up until the array contains a

`-1`

`-1`

I am doing that calculation like this:

`function calculate (){`

logingValues();

var total = 0;

var shouldSubtract = false;

for (var i = 0; i < arrayOfNumbers.length; i++) {

if (arrayOfNumbers[i] === "") continue;

var currentNumber = parseInt(arrayOfNumbers[i], 10);

if(isNaN(currentNumber)) {

currentNumber = 0;

}

if (currentNumber === -1) {

shouldSubtract = true;

} else {

if (shouldSubtract) {

total -= currentNumber;

shouldSubtract = false;

} else {

total += currentNumber;

}

}

}

caculationEffect(total);

}

And here is the whole code

Any suggestions?

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You could use a variable for the deciding if to add or subtract the actual value.

```
function sum(array){
var negative;
return array.reduce(function (a, b) {
if (b === -1) {
negative = !negative;
return a;
}
return negative ? a - b : a + b;
}, 0);
}
console.log(sum([1, 5, 10]));
console.log(sum([1, 5, -1, 10, 5]));
console.log(sum([1, 5, -1, 10, 5, -1, 5, 5]));
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**