How to use ForEach() Method In Javascript
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.
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 ]
Print Odd Numbers in a JavaScript Array
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.
Table of Content
- Using JavaScript Filter() Method
- Using JavaScript ForEach() Method
- Using JavaScript For Loop
- Using JavaScript For…of Loop
- Using Array.prototype.reduce