1

Hey guys working on a problem from CoderBytes. The directions of the following:

Using the JavaScript language, have the function DashInsert(num) insert dashes ('-') between each two odd numbers in num. For example: if num is 454793 the output should be 4547-9-3. Don't count zero as an odd number.

Use the Parameter Testing feature in the box below to test your code with different arguments.

So I didn't create a function but here is my road map.

num = 3333333333
arr = num.toString().split("")
for(var i = 0; i < arr.length; i++){
    if(arr[i] % 2 === 1 && arr[i + 1] % 2 === 1){
        num.toString().replace(arr[i].toString() + arr[i+1].toString(),
                    arr[i].toString() + "-" + arr[i+1].toString())
    }

    }

The thing is when I run this it only puts a dash between the first two threes. I really can't figure out why this is happening. Anyone know where I am going wrong?

1
  • semi-colons (;) are your friend! Commented Sep 22, 2014 at 5:47

1 Answer 1

3

Here, this simple solution should do well:

var num = 3434333333
var arr = num.toString().split("");
var finalStr = "";
for(var i = 0; i < arr.length; i++){
    if(arr[i] % 2 === 1 && arr[i + 1] % 2 === 1){
        finalStr += arr[i] + "-";
    }
    else {
        finalStr += arr[i];
    }
}

simply keep a string for the result, if two consecutive numbers are odd append an extra "-" after the number in the string, otherwise simply append the number and your final string will contain the desired result.

See the DEMO here

Sign up to request clarification or add additional context in comments.

3 Comments

you're welcome and dont forget to mark the answer correct as well (:
The limit should be i < arr.length - 1 then just concatenate the last number at the end since there is no point in testing it. Consider: finalStr += arr[i] + (arr[i]%2 && arr[i+1]%2? '-' : '');. ;-)
@RobG you're right but that one liner would have got a little complex for any beginner to understand so i kept it as simple as i could..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.