- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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]
Advertisements