How To Find The Odd Numbers In An Array In JavaScript

To find Odd numbers in an array in JavaScript, you can use the for loop, the forEach() method, and the filter() method. Let’s go.

Table of Contents

Find the Odd numbers in an array in JavaScript

The Odd numbers are numbers that are not divisible by 2. To find the Odd numbers in an array, we will iterate over all the elements of the array. At each loop, we check if the element is divisible by 2. Otherwise, the element is Odd.

We will go into each solution with specific examples to find the Odd numbers in an array in JavaScript.

Using the for loop

We use a for loop to iterate through the original array’s elements. At each loop, if the element is the Odd number, it will be pushed into a new array.

Example:

// Create an array of number
const numArray = new Array(1, 2, 3, 4, 5, 6);

// Create an empty array
const oddArray = new Array();

// If element is not divisible by 2 => push to 'oddArray' array
for (let i = 0; i < numArray.length; i++) {
if (numArray[i] % 2 !== 0) {
oddArray.push(numArray[i]);
}
}

console.log(oddArray);

Output:

[ 1, 3, 5 ]

Using the forEach() method

The forEach() method calls a function for each element in an array.

In this solution, we use the forEach() method to call a function for each element of the original array. This function will check the element. If the element is an Odd number, it will push to the new array.

Example:

// Create an array of number
const numArray = new Array(1, 2, 3, 4, 5, 6);

// Create an empty array
const oddArray = new Array();

// If the element is not divisible by 2 => push to 'oddArray' array
numArray.forEach((num) => {
if (num % 2 !== 0) {
oddArray.push(num);
}
});

console.log(oddArray);

Output:

[ 1, 3, 5 ]

Using the filter() method

The filter() method returns a new array of the original array elements that meet the callback function’s condition.

Syntax:

array.filter(callback function)

Parameters:

callback function: Function that is called for every array element.

The following example describes how we find the Odd numbers in an array using the filter() method.

Example:

// Create an array of number
const numArray = new Array(1, 2, 3, 4, 5, 6);

// Find the Odd numbers in the 'numArray' array using the filter() method
const oddArray = numArray.filter((num) => {
return num % 2 !== 0;
});

console.log(oddArray);

Output:

[ 1, 3, 5 ]

Summary

This article shared three solutions to find Odd numbers in an array in JavaScript using the for loop, the forEach() method, and the filter() method. You can use any solution for your program. If you need to find the Odd numbers multiple times, build a reusable function. Thank you for reading.