JavaScript Program to Count Positive and Negative Numbers in an Array
Last Updated :
23 Jul, 2025
Given an array of numbers. Write a JavaScript program to count positive and negative numbers in an array.
Example:
Input: numbers_array1= [10,20, -1,22,99,20, -9]
Output: positive no's=5, negative no's =2
Input: numbers_array2= [-121, - 78, -13, 54, -23]
Output: positive no's=1, negative no's=4
Brute Force Approach
We will be using the javascript for loop to iterate in the array and make sure to count each positive and negative number.
Example 1: This code counts positive and negative numbers from the given array using JavaScript for loop. Iterate each element in the list using a for loop and check if (num >= 0), the condition to check negative numbers. If the condition is satisfied, then increase the negative count else increase the positive count.
JavaScript
let numbers= [10,-12,89,56,-83,8,90,-8]
let pos_count=neg_count=0;
for(let i=0;i<numbers.length;i++){
if (numbers[i]<0)
neg_count++;
else
pos_count++;
}
console.log(`The positive numbers in an array is ${pos_count}`)
console.log(`The negative numbers in an array is ${neg_count}`)
OutputThe positive numbers in an array is 5
The negative numbers in an array is 3
Using Recursion
Example: In this example, we are going to use the recursion approach that will help us to recursively call the CountNumbers Functions and it will find the positive and negative numbers and store them to the variables.
JavaScript
function countNumbers(numbers, index, pos_count, neg_count) {
if (index < numbers.length) {
if (numbers[index] < 0) {
neg_count++;
} else {
pos_count++;
}
return countNumbers(numbers, index + 1, pos_count, neg_count);
} else {
return { pos_count, neg_count };
}
}
let numbers= [-8,10,23,44,-80,-15,-1]
let counts = countNumbers(numbers, 0, 0, 0);
console.log(`The positive numbers in an array is ${counts.pos_count}`)
console.log(`The negative numbers in an array is ${counts.neg_count}`)
OutputThe positive numbers in an array is 3
The negative numbers in an array is 4
Using filter() Method
Example: We are going to use the javascript built in filter() method that will filter out the positive and negative numbers respectively.
JavaScript
let numbers= [-8,10,23,44,-80,-15,-13,-1]
let positiveNumbers = numbers.filter(function(number) {
return number >= 0;
});
let negativeNumbers = numbers.filter(function(number) {
return number < 0;
});
console.log(`The positive numbers in an array is ${positiveNumbers.length}`)
console.log(`The negative numbers in an array is ${negativeNumbers.length}`)
OutputThe positive numbers in an array is 3
The negative numbers in an array is 5
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics