In this article, we’ll be looking at different ways to find the odd numbers in an array using JavaScript.
1. Array filter() Method
To find the odd numbers in an array, we can call the Array
filter()
method, passing a callback that returns true
when the number is odd, and false
otherwise.
const numbers = [8, 19, 5, 6, 14, 9, 13];
const odds = numbers.filter((num) => num % 2 === 1);
console.log(odds); // [19, 5 , 9, 13]
The filter()
method creates a new array with all the elements that pass the test specified in the testing callback function. So, filter()
returns an array of all the odd numbers in the original array.
2. Array forEach() Method
Another way to find the odd numbers in a JavaScript array is with the Array
forEach()
method. We call forEach()
on the array, and in the callback, we only add an element to the resulting array if it is odd. For example:
const numbers = [8, 19, 5, 6, 14, 9, 13];
const odds = [];
numbers.forEach((num) => {
if (num % 2 === 1) {
odds.push(num);
}
});
console.log(odds); // [19, 5, 9, 13]
3. for…of Loop
We can use the for...of
loop in place of forEach()
to iterate through the array:
const numbers = [8, 19, 5, 6, 14, 9, 13];
const odds = [];
for (const num of numbers) {
if (num % 2 === 1) {
odds.push(num);
}
}
console.log(odds); // [19, 5, 9, 13]
Every Crazy Thing JavaScript Does
A captivating guide to the subtle caveats and lesser-known parts of JavaScript.