JavaScript Code


How to filter odd numbers in array using JavaScript?


Filter odd numbers in array in JavaScript

In this tutorial, you are given an array. Write a JavaScript program to filter odd numbers in the array.

Solution

To filter odd numbers in the given array using JavaScript, we can use Array.filter() method. Call filter() method on the given array, and pass a function that returns true for odd number, or false otherwise. filter() method returns a new array with the odd numbers from the contents of original array.

Program

1. Filter odd numbers in the nums array.

function isOdd(item) {
    if (item % 2 == 1) {
        return true;
    } else {
        return false;
    }
}

nums = [4 , 5, 2, 0, 1, 7, 19, 82];
oddNums = nums.filter(isOdd);
console.log(oddNums);



copyright @2022