I am trying to make a javascript function that, given a number n , separates its odd digits from the pairs with the character '-'
.. if they are 2 consecutive pairs they are not separated, consecutive odd ones are separated ..
Ex1:
function separarImpares(24589)
->(24-5-8-9)
Ex2:
function separarImpares(132479)
->(1-3-24-7-9)
I put a code example of what I have tried. Thanks.
function separarImpares(num) {
let str="";
num = `${num}`.split('');
for(var i=0; i<num.length; i++){
switch (num[i]) {
case (num[i]%2==0 & num[i+1]%2!=0 ):
str+=`${num[i]}-`;
console.log(num[i]);
break;
case (num[i]%2!=0 & num[i+1]%2!=0):
str+=`${num[i]}-`;
break;
case (num[i]%2!=0 & num[i+1]%2==0):
str+=`${num[i]}-`;
break;
default:
str+=`${num[i]}`
break;
}
}
return str
}
console.log(separarImpares(6815))
Using a regular expression
split()
would be a totally different approach and reduces the code a bit:Iterating, I would use
[...'${num}']
to pass from number to array and then%2
for each number:I can propose 2 approaches on how to solve it in a very simplified way:
1. You can iterate through the number and ask digit by digit if it is odd or not, then accumulate the result in a string:
It is used
toString()
to pass the number to a string, thensplit('')
to divide the number andmap()
to go through the array and accumulate the digits in a string (nsi
) that will then be returned as a result.To remove the excess dashes and those at the beginning and end of the result you can use:
2. You can loop through an array of odd numbers by replacing each odd digit in the string with the same one with hyphens using
split()
andjoin()
:The same function is used to remove excess hyphens. Although this method could be less optimal, there is another way to solve it. Greetings.
Taking from the 2 answers I also made this function and I share it... thanks to @Emeeus and @the-breaker..
Another thing... if the number is negative odd then there would be a
'--'
at the beginning of the number and if it is negative even it would be negative (a'-'
) something that may not interest you if you are treating the number as a string to be separated, this would be easier depends on what you want to do (leave it negative without the double -- or the first negative even number which you can do with areplace('--', '-)
))Show as a string