- 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
Splitting number to contain continuous odd or even number using JavaScript
Problem
We are required to write a JavaScript function that takes in a number n(n>0). Our function should return an array that contains the continuous parts of odd or even digits. It means that we should split the number at positions when we encounter different numbers (odd for even, even for odd).
Example
Following is the code −
const num = 124579; const splitDifferent = (num = 1) => { const str = String(num); const res = []; let temp = ''; for(let i = 0; i < str.length; i++){ const el = str[i]; if(!temp || +temp[temp.length - 1] % 2 === +el % 2){ temp += el; }else{ res.push(+temp); temp = el; }; }; if(temp){ res.push(+temp); temp = ''; }; return res; }; console.log(splitDifferent(num));
Output
[ 1, 24, 579 ]
Advertisements