To find the odd numbers in an array, follow the following steps:
filter()
method on the array in which you want to find odd numbers.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:
forEach()
method on the array in which you want to find odd numbers.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.