How to use Array.prototype.reduce In Javascript
In this approach we will use reduce method which is used to accumulate values from an array into a single result. In this case it accumulates odd numbers from the array into a new array. For each element, it checks if it’s odd (not divisible by 2) and adds it to the accumulator array if it is.
Example: Printing odd number in JavaScript array using reduce method.
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let oddNumbers = array.reduce((accumulator, currentValue) => {
if (currentValue % 2 !== 0) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(oddNumbers);
Output
[ 1, 3, 5, 7, 9 ]
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
Contact Us