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
How to create a function which returns only even numbers in JavaScript array?
Here, we need to write a function that takes one argument, which is an array of numbers, and returns an array that contains only the numbers from the input array that are even.
So, let's name the function as returnEvenArray, the code for the function will be ?
Example
const arr = [3, 5, 6, 7, 8, 4, 2, 1, 66, 77];
const returnEvenArray = (arr) => {
return arr.filter(el => {
return el % 2 === 0;
})
};
console.log(returnEvenArray(arr));
We just returned a filtered array that only contains elements that are multiples of 2.
Output
Output in the console will be ?
[ 6, 8, 4, 2, 66 ]
Above, we returned only even numbers as output.
Alternative Methods
Using for Loop
const arr = [3, 5, 6, 7, 8, 4, 2, 1, 66, 77];
function getEvenNumbers(numbers) {
const evenNumbers = [];
for (let i = 0; i < numbers.length; i++) {
if (numbers[i] % 2 === 0) {
evenNumbers.push(numbers[i]);
}
}
return evenNumbers;
}
console.log(getEvenNumbers(arr));
[ 6, 8, 4, 2, 66 ]
Using forEach Method
const arr = [3, 5, 6, 7, 8, 4, 2, 1, 66, 77];
function extractEvenNumbers(numbers) {
const result = [];
numbers.forEach(num => {
if (num % 2 === 0) {
result.push(num);
}
});
return result;
}
console.log(extractEvenNumbers(arr));
[ 6, 8, 4, 2, 66 ]
Comparison
| Method | Performance | Readability | Best Use Case |
|---|---|---|---|
filter() |
Fast | Excellent | Functional programming style |
for loop |
Fastest | Good | Performance-critical applications |
forEach() |
Moderate | Good | When you need side effects |
Conclusion
The filter() method provides the most concise and readable solution for extracting even numbers from an array. Use alternative methods when specific performance requirements or coding styles are needed.
Advertisements
