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
Returning an array containing last n even numbers from input array in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of numbers as the first argument and a number as the second argument.
Our function should pick and return an array of last n even numbers present in the input array.
Example
Following is the code ?
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const num = 3;
const pickEvens = (arr = [], num = 1) => {
const res = [];
for(let index = arr.length - 1; index >= 0; index -= 1){
if (res.length === num){
break;
};
const number = arr[index];
if (number % 2 === 0){
res.unshift(number);
};
};
return res;
};
console.log(pickEvens(arr, num));
[4, 6, 8]
How It Works
The function uses a reverse loop to traverse the array from the last element. When it finds an even number (number % 2 === 0), it adds it to the beginning of the result array using unshift(). This maintains the original order of the last n even numbers.
Alternative Approach Using filter() and slice()
Here's a more concise approach using built-in array methods:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12];
const num = 4;
const pickEvensAlternative = (arr = [], num = 1) => {
return arr.filter(number => number % 2 === 0).slice(-num);
};
console.log(pickEvensAlternative(arr, num));
[6, 8, 10, 12]
Comparison
| Method | Performance | Readability | Memory Usage |
|---|---|---|---|
| Reverse Loop | Better (stops early) | Moderate | Lower |
| filter() + slice() | Slower (processes all elements) | Higher | Higher |
Edge Cases
// When array has fewer even numbers than requested console.log(pickEvens([1, 3, 5, 7, 8], 3)); // [8] // When num is 0 console.log(pickEvens([2, 4, 6], 0)); // [] // Empty array console.log(pickEvens([], 2)); // []
[8] [] []
Conclusion
The reverse loop approach is more efficient for large arrays as it stops early when the required count is reached. Use the filter-slice method for better readability in smaller datasets.
