I was solving an exercise with array methods; where I was expected to input a number and the returned value should be the same number with dashes between each two consecutive even numbers.
I have wrote this code so far but It's returning an empty array, It would be much better if you could point out my mistakes than giving an alternative solution.
function dashit(num){
//test num = 025468, expected arr = ["0","-","2","5","4","-","6","- ","8"]
var arr = [];
var prog = num.toString().split(""); // I suppose ["0","2","5","4","6","8"]
for (var i = 0; i<num.length; i = i + 2){
if (num[i] % 2 == 0 ){ // case of "0" and "2"
if (num[i+1] % 2 == 0){
arr.push(prog[i]); // "0" pushed from prog to arr
arr.push("-"); // "-" pushed from prog to arr
arr.push(prog[i+1]); // "2" pushed from prog to arr
}
}
else { // case of "5" and "4"
arr.push(prog[i]); // "5" pushed from prog to arr
arr.push(prog[i+1]); // "4" pushed from prog to arr
}
}
return arr;
}
numis an actual number (as in the comment), andnum[i]doesn't make sense, but your debugger will tell you everything you need to knownum.lengthisundefined. Did you meanprog.length? Same with all the othernumuses. Why are you usingnumin same cases andprogin others?/(\d+)/regex may be more suitable. Is there any reason you're rolling your own solution?