Open In App

Print all Positive Numbers in JavaScript Array

Last Updated : 13 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, arrays are the data structures used to store multiple elements. In some cases, we need to extract the elements that satisfy a specified condition. We can use a condition to extract all the positive numbers from an array with the below approaches.

Example:

Input: arr = [-1, -12, 35, -8, 45, 68, 99]
Output: 35, 45, 68, 99 all positive numbers.

Using for Loop

In this approach, we are using the for loop to iterate over each element of the array and check if each element is greater than 0, which means a positive number.

Syntax:

for (initialization; condition; increment/decrement) {
// code
}

Example: The below code example uses the for loop to print all positive numbers in a JavaScript array.

Javascript




let arr =
    [12, 34, 13, -1, -4, 45, -55, -66];
 
for (let i = 0; i < arr.length; i++) {
    if (arr[i] > 0) {
        console.log(arr[i]);
    }
}


Output

12
34
13
45

Using forEach method

In this approach, we are using the forEach method to iterate over each element of the array and get each of the positive numbers.

Syntax:

array.forEach(function(currentValue, index, array) {
// code
});

Example: The below code example uses the forEach method to print all positive numbers from a JavaScript array.

Javascript




let arr =
    [12, 34, 13, -1, -4, 45, -55, -66];
 
arr.forEach(number => {
    if (number > 0) {
        console.log(number);
    }
});


Output

12
34
13
45

Using filter method

In this approach, we are using the built-in filter method to create the new array which consists of only the positive numbers from the input array.

Syntax:

const res = array.filter(function(currentValue, index, array) {
// code
});

Example: The below code example uses the filter method to print all positive numbers from a JavaScript array.

Javascript




let arr =
    [12, 34, 13, -1, -4, 45, -55, -66];
let res =
    arr.filter(number => number > 0);
console.log(res);


Output

[ 12, 34, 13, 45 ]

Using for…of Loop

In this approach, we are using the for…of loop to iterative over each element of the input arr and check if the number of the array is greater than 0. If the number is greater than 0, then it is printed in the console.

Syntax:

for (variable of iterable) {
// code
}

Example: The below code example uses the for…of Loop to print all positive numbers from a JavaScript array.

Javascript




let arr =
    [12, 34, 13, -1, -4, 45, -55, -66];
 
for (let number of arr) {
    if (number > 0) {
        console.log(number);
    }
}


Output

12
34
13
45


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads