JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

How to find odd numbers in an array using JavaScript?

To find the odd numbers in an array, follow the following steps:

  1. First, call the filter() method on the array in which you want to find odd numbers.
  2. Specify the condition inside the callback function of the filter() method. The condition must use the modulo operator (%) to check if a number is divisible by 2 or not.
  3. If a number is not divisible by 2, then return true, and that array element becomes a member of the new array.
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

let oddNumbers = numbers.filter(number => {
  if(number % 2 !== 0){
    return true;
  }
});
console.log(oddNumbers); //[1, 3, 5, 7, 9]

Note: The filter() method does not modify the original array.

It is important to note that the filter() method accepts a callback function. This callback function is called for each element of the array. Inside the callback function, you check if a number is divisible by 2 or not, and for this, use the modulo operator (%). If the value returned by the modulo operator is 0, then the number is divisible by 2; otherwise, it is not divisible by 2.

If a number is not divisible by 2, then return true so that it becomes a part of the new array, and in this way, you can find odd numbers in an array.

In case you don't want to use the filter() method, you can use the forEach() method.

To find the odd numbers in an array using the forEach() method, follow the following steps:

  1. First, create an empty array in which you will store the odd numbers of the array.
  2. Call the forEach() method on the array in which you want to find odd numbers.
  3. Specify the condition inside the callback function of the forEach() method. The condition will check if a number is divisible by 2 or not.
  4. If the number is not divisible by 2, then push that array element to the new array created in step 1.
let oddNumbers = [];
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

numbers.forEach(number => {
  if(number % 2 !== 0){
    oddNumbers.push(number);
  }
});
console.log(oddNumbers); //[1, 3, 5, 7, 9]

Note: The forEach() method does not modify the original array.

The forEach() method is used to iterate through the array. It accepts a callback function. This callback function is called on each element of the array.

Recommended Posts