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
Finding even length numbers from an array in JavaScript
We are required to write a JavaScript function that takes in an array of integers as the first and the only argument. The function should then construct and return a new array that contains only those elements from the original array that have an even number of digits.
For example, if we have an array with numbers of different digit lengths, we need to filter out only those numbers whose digit count is even (2, 4, 6, etc.).
Problem Example
If the input array is:
const arr = [12, 6, 123, 3457, 234, 2];
Let's analyze the digit count for each number:
- 12 ? 2 digits (even) ?
- 6 ? 1 digit (odd) ?
- 123 ? 3 digits (odd) ?
- 3457 ? 4 digits (even) ?
- 234 ? 3 digits (odd) ?
- 2 ? 1 digit (odd) ?
Then the output should be:
[12, 3457]
Using For Loop
const arr = [12, 6, 123, 3457, 234, 2];
const findEvenDigitsNumber = (arr = []) => {
const res = [];
const { length: l } = arr;
for(let i = 0; i < l; i++){
const num = Math.abs(arr[i]);
const numStr = String(num);
if(numStr.length % 2 === 0){
res.push(arr[i]);
};
};
return res;
};
console.log(findEvenDigitsNumber(arr));
[12, 3457]
Using Array.filter() Method
A more concise approach using the built-in filter() method:
const arr = [12, 6, 123, 3457, 234, 2];
const findEvenDigitsNumber = (arr = []) => {
return arr.filter(num => {
const digitCount = String(Math.abs(num)).length;
return digitCount % 2 === 0;
});
};
console.log(findEvenDigitsNumber(arr));
[12, 3457]
Handling Negative Numbers
Both approaches use Math.abs() to handle negative numbers correctly, counting only the actual digits without the minus sign:
const arrWithNegatives = [12, -6, -123, 3457, -234, 2];
const findEvenDigitsNumber = (arr = []) => {
return arr.filter(num => {
const digitCount = String(Math.abs(num)).length;
return digitCount % 2 === 0;
});
};
console.log(findEvenDigitsNumber(arrWithNegatives));
[12, 3457]
Comparison
| Method | Readability | Code Length | Performance |
|---|---|---|---|
| For Loop | Good | More verbose | Slightly faster |
| Array.filter() | Excellent | Concise | Good |
Conclusion
Both methods effectively filter numbers with even digit counts. The filter() approach is more readable and functional, while the for loop offers slightly better performance for large arrays.
