Fetch Numbers with Even Number of Digits JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Numbers as the only argument.

The function should pick all those elements from the array that contains an even number of digits and return them in a new array.

For example −

If the input array is −

const arr = [34, 23, 112, 8, 3456, 345];

Then the output should be −

const output = [34, 23, 3456];

Example

const arr = [34, 23, 112, 8, 3456, 345];
const countDigits = (num, sum = 0) => {
   if(num){
      return countDigits(Math.floor(num / 10), sum + 1);
   };
   return sum;
};
const isEven = num => num % 2 === 0;
const returnEvens = (arr = []) => {
   const res = arr.filter(el => isEven(countDigits(el)));
   return res;
};
console.log(returnEvens(arr));

Output

And the output in the console will be −

[34, 23, 3456]
raja
Published on 25-Nov-2020 07:49:10
Advertisements