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
Fetch Numbers with Even Number of Digits JavaScript
In JavaScript, finding numbers with an even count of digits means identifying numbers where the total digit count is divisible by 2. This is different from finding even numbers themselves.
Understanding the Problem
We need to create a function that takes an array of numbers and returns only those numbers that have an even number of digits. For example, in the array [12, 345, 67, 8910, 11, 9], the numbers 12 (2 digits), 67 (2 digits), and 8910 (4 digits) have even digit counts.
Method 1: Using String Length
Convert each number to a string and check if its length is even:
function numbersWithEvenDigits(arr) {
let result = [];
for (let i = 0; i
Numbers with even digit count: [ 12, 67, 8910 ]
Method 2: Using Mathematical Approach
Count digits using logarithm instead of string conversion:
function numbersWithEvenDigitsMath(arr) {
let result = [];
for (let num of arr) {
// Handle special case of 0
let digitCount = num === 0 ? 1 : Math.floor(Math.log10(Math.abs(num))) + 1;
if (digitCount % 2 === 0) {
result.push(num);
}
}
return result;
}
const testArray = [1, 23, 456, 7890, 0, -123];
console.log("Result:", numbersWithEvenDigitsMath(testArray));
// Test individual digit counts
testArray.forEach(num => {
let digitCount = num === 0 ? 1 : Math.floor(Math.log10(Math.abs(num))) + 1;
console.log(`${num} has ${digitCount} digits`);
});
Result: [ 23, 7890 ]
1 has 1 digits
23 has 2 digits
456 has 3 digits
7890 has 4 digits
0 has 1 digits
-123 has 3 digits
Method 3: Using Filter Method
A more concise approach using array filter:
function filterEvenDigitNumbers(arr) {
return arr.filter(num => {
let digitCount = Math.abs(num).toString().length;
return digitCount % 2 === 0;
});
}
const mixedNumbers = [5, 44, 333, 2222, 55555, 666666];
console.log("Original array:", mixedNumbers);
console.log("Even digit count numbers:", filterEvenDigitNumbers(mixedNumbers));
Original array: [ 5, 44, 333, 2222, 55555, 666666 ]
Even digit count numbers: [ 44, 2222, 666666 ]
Comparison
| Method | Approach | Readability | Performance |
|---|---|---|---|
| String Length | Convert to string | High | Good |
| Mathematical | Use logarithm | Medium | Better |
| Filter Method | Functional approach | High | Good |
Complexity Analysis
All methods have O(n) time complexity where n is the array length, as each element must be processed once. Space complexity is O(k) where k is the count of numbers with even digits in the result array.
Conclusion
Use the string length method for simplicity and readability. The filter approach provides clean, functional code, while the mathematical method offers slightly better performance for large datasets.
