Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Returning array values that are not odd in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers.
Our function should construct and return a new array that contains all the numbers of the input array that are not odd (i.e., even numbers).
Example
Following is the code ?
const arr = [5, 32, 67, 23, 55, 44, 23, 12];
const findNonOdd = (arr = []) => {
const res = [];
for(let i = 0; i < arr.length; i++){
const el = arr[i];
if(el % 2 !== 1){
res.push(el);
}
}
return res;
};
console.log(findNonOdd(arr));
Output
[ 32, 44, 12 ]
Alternative Methods
Using filter() Method
A more concise approach using the built-in filter() method:
const arr = [5, 32, 67, 23, 55, 44, 23, 12]; const findNonOdd = (arr = []) => arr.filter(num => num % 2 === 0); console.log(findNonOdd(arr));
[ 32, 44, 12 ]
Using forEach() Method
Another approach using forEach() for iteration:
const arr = [5, 32, 67, 23, 55, 44, 23, 12];
const findNonOdd = (arr = []) => {
const res = [];
arr.forEach(num => {
if(num % 2 === 0) {
res.push(num);
}
});
return res;
};
console.log(findNonOdd(arr));
[ 32, 44, 12 ]
How It Works
The key concept is using the modulo operator (%) to check if a number is even:
-
num % 2 === 0- checks if number is even -
num % 2 !== 1- alternative way to check for even numbers - Even numbers have no remainder when divided by 2
Comparison
| Method | Performance | Readability | Lines of Code |
|---|---|---|---|
| For loop | Fastest | Good | More |
| filter() | Good | Excellent | Least |
| forEach() | Good | Good | Medium |
Conclusion
The filter() method provides the most readable and concise solution for finding non-odd (even) numbers. For performance-critical applications, the traditional for loop remains the fastest approach.
Advertisements
