Find the Odd Numbers in an Array using JavaScript

Borislav Hadzhiev

Wed Oct 27 2021ยท2 min read

Photo by Jake Roxen

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

- Call the
`filter()`

method, passing it a function. - On each iteration use the modulo operator to check that the number has a remained when divided by 2.
- The
`filter`

method returns a new array containing the elements that satisfy the condition.

index.js

Copied!`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`

.

If there is a remainder, we can conclude that the number is odd.

**Only odd numbers satisfy our condition and will be included in the array
that the filter method returns.**

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

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

- Create a new array that will store the odd numbers.
- Use the
`forEach`

method to iterate over the array and on each iteration check that the number has a remainder when divided by 2. - If there is a remainder, push the number to the odd numbers array.

index.js

Copied!`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 also gets called with each
element in the array.

However the `forEach`

method doesn't return an array like `filter`

does.

The

`forEach`

method returns `undefined`

, so we have to create a new array that will store our state.Once the method has iterated over the entire array the `odds`

variable will
contain all odd numbers from the original array.

I'll send you 1 email a week with links to all of the articles I've written that week