Find the Odd Numbers in an Array using JavaScript

Borislav Hadzhiev

Last updated: Jul 25, 2022

Check out my new book

**To find the odd numbers in an array:**

- Use the
`filter()`

method to iterate over the array. - Check if each number has a remainder when divided by 2.
- The
`filter`

method will return a new array containing only the odd numbers.

index.js

`const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const odds = arr.filter(number => { return number % 2 !== 0; }); console.log(odds); // 👉️ [1, 3, 5, 7, 9]`

The function we passed to the Array.filter method gets called with each element in the array.

If the function returns a truthy value, the element is included in the new array the

`filter`

method returns.On each iteration, we use the
modulo (%)
operator to check if the number has a remainder when divided by `2`

.

index.js

`console.log(10 % 2); // 👉️ 0 console.log(11 % 2); // 👉️ 1`

If there is a remainder, then the number is odd.

**Only odd numbers meet the condition and get added to the new array.**

An alternative approach is to use the Array.forEach method.

**To find the odd numbers in an array:**

- Declare a new variable and set it to an empty array.
- Use the
`forEach`

method to iterate over the array - Check if each number has a remainder when divided by 2.
- If there is a remainder, push the number into the odd numbers array.

index.js

`const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const odds = []; arr.forEach(number => { if (number % 2 !== 0) { odds.push(number); } }); console.log(odds); // 👉️ [1, 3, 5, 7, 9]`

The function we passed to the `forEach()`

method gets called with each element
in the array.

We check if each number has a remainder when divided by

`2`

and push the odd numbers into the new array.Once the `forEach`

method has iterated over the entire array, the `odds`

variable will contain all odd numbers from the original array.

Which approach you pick is a matter of personal preference. I'd go with the
`filter()`

method as it helps us avoid declaring an intermediary variable.

Use the search field on my Home Page to filter through my more than 3,000 articles.