Fetch Numbers with Even Number of Digits JavaScript


In the given problem statement our task is to write the function for fetching the numbers with an even number of digits with the help of Javascript. For solving this task we will use a for loop and push every even number in the array.

Understanding the problem statement

The problem statement is to write a function which will take an array of numbers as input and return the array for containing only numbers that have an even number of digits. For example if we have an input array is [1 ,2 , 3, 4, 5] the function should return [2, 4] because in this array both the numbers are even and divisible by 2.

Logic for the above problem

To solve this problem we will iterate whole elements of the input array and with the usage of for loop and if condition fetch the even digits from the array. And after getting the even numbers we will push them in an array. At the end we will have processed all the numbers in the input array so we can return the new array which will have only the even digit numbers.

Algorithm

Step1 − Define a function to get the even numbers from the given array.

Step2 − Initialize a blank array to store the result array of even numbers.

Step3 − Use a for loop and this loop will run until the length of the array.

Step4 − Check the condition for every item of the array to get the even number.

Step5 − Push the result array of even numbers.

Step6 − Return the result and call the function we have created above to get the output on console.

Code for the algorithm

//functio to get the even numbers
function evenNumbers(arr) {
   //result array to store the even numbers
   let result = [];

   for (let i = 0; i < arr.length; i++) {
      if (arr[i] % 2 === 0) {
         result.push(arr[i]);
      }
   }
   return result;
}
const arr = [12, 345, 67, 8910, 11, 9];
const even = evenNumbers(arr);
console.log(even);

Complexity

The time taken by this code is O(n) in which n is the length of the input array. Because the program performs a single iteration through the array and performs a constant time for every item in the array. The space complexity of the program is also O(n) as the result array stores all the even numbers from arr.

Conclusion

The program effectively fetch all even numbers from an input array. And the time taken by the function to execute and produce the result is O(n) and space consumed is also O(n).

Updated on: 18-May-2023

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements