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 −

 Live Demo

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 ]

Updated on: 19-Apr-2021

192 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements