EN
JavaScript - sum only negative numbers in array
0
points
In this article, we would like to show you how to sum only negative numbers in array using JavaScript.
Quick solution:
// ONLINE-RUNNER:browser;
var numbers = [-1, -2, -3, 4, 5, 6];
var result = 0;
for (var i = 0; i < numbers.length; ++i) {
if (numbers[i] < 0) {
result += numbers[i];
}
}
console.log(result); // -6
Practical example
In this example, we create a reusable arrow function that checks if a number is negative and sums it up.
// ONLINE-RUNNER:browser;
const sumNegative = (numbers) => {
let result = 0;
for (let i = 0; i < numbers.length; ++i) {
if (numbers[i] < 0) {
result += numbers[i];
}
}
return result;
};
// Usage example:
const result = sumNegative([-1, -2, -3, 4, 5, 6]);
console.log(result); // -6