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 contains an even number of digits.

For example −

If the input array is −

const arr = [12, 6, 123, 3457, 234, 2];

Then the output should be −

const output = [12, 3457];

Example

The code for this will be −

 Live Demo

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));

Output

And the output in the console will be −

[12, 3457]

Updated on: 26-Feb-2021

321 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements