Open In App

Print Odd Numbers in a JavaScript Array

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

JavaScript provides us with various approaches for printing odd numbers in an array. The core concept behind finding an odd number is based on the fundamental arithmetic property that odd numbers leave a remainder of 1 when divided by 2.

Using JavaScript Filter() Method

JavaScript Array filter() Method is used to create a new array from a given array. The new array only consists of those elements which satisfy the conditions set by the argument function. Here we check whether each number when divided by 2 leaves a remainder of 1 to check if it is a odd number or not.

Example: Printing odd number in Javascript array using filter() method.

Javascript




const arr = [1 , 2, 4, 9, 12, 13, 20];
const oddNumbers = arr.filter((num) => num%2 === 1);
console.log(oddNumbers);


Output

[ 1, 9, 13 ]

Using JavaScript ForEach() Method

The Array.forEach() method performs the operation on each element of the array. We can perform any operation on the each element of the given array. Here we again do the same and check if each element in the array is odd or not but we also use the “&&” conditions to only push the odd numbers in the new Array.

Example: Printing odd number in JavaScript array using forEach() method.

Javascript




const arr = [1 , 2, 4, 9, 12, 13, 20];
const oddNumbers = [];
arr.forEach((num) => num % 2 === 1 && oddNumbers.push(num));
console.log(oddNumbers);


Output

[ 1, 9, 13 ]

Using JavaScript For Loop

In this method we will use the classic for loop to traverse the array and check if each element is odd or not and if it is odd then we will push only that element in the resulting oddNumbers Array. Here we again do the same and check if each element in the array is odd or not but we access the elements from their index in the array and we also use the “&&” conditions to only push the odd numbers in the new Array.

Example: Printing odd number in JavaScript using for loop.

Javascript




const arr = [1 , 2, 4, 9, 12, 13, 20];
const oddNumbers = []
for(let i = 0; i < arr.length; i++){
    arr[i] % 2 === 1 && oddNumbers.push(arr[i]);
}
console.log(oddNumbers);


Output

[ 1, 9, 13 ]

Using JavaScript For…of Loop

This For…of Loop in JavaScript works in the same way as the for Loop where we can perform any operation on each element of the given array but it makes it easier as we don’t have to handle the index of the array to traverse the array.

Example: Printing odd number in JavaScript array suing for of loop.

Javascript




const arr = [1 , 2, 4, 9, 12, 13, 20];
const oddNumbers = []
for(const num of arr){
    num % 2 === 1 && oddNumbers.push(num);
}
console.log(oddNumbers);


Output

[ 1, 9, 13 ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads