How do i return the result of all loops in javascript?

Viewed 83

I am trying to insert dashes ('-') between each two odd numbers and insert asterisks ('*') between each two even numbers, but I am only getting the last result.

I want to print out all the elements in the array.

For example: if num is 4546793 the output should be 454*67-9-3. I Did not count zero as an odd or even number.

function StringChallenge(num) {
  let result = "";
  for (let i = 0; i < num.length; i++) {
    if (num[i] === 0) {
      continue;
    }

    if (num[i - 1] % 2 == 0 && num[i] % 2 == 0) {
      result = num[i - 1] + "*" + num[i];
      continue;
    }
    if (num[i - 1] % 2 == !0 && num[i] % 2 == !0) {
      result = num[i - 1] + "-" + num[i];
      continue;
    }
  }
  return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));

6 Answers

You do not need to check as if&continue. Inserting given numbers to the result string and only adding "-" when index and previous are odd, and "*" when index and previous are even.

function StringChallenge(num) {
  let result = "";
  for (let i = 0; i < num.length; i++) {
    if (num[i]%2 ===0) {// even
      if(i !== 0 && num[i-1]%2===0){// previous is even either
        result+="*"+num[i];
      }else{
        result+=num[i];
      }
    }else{// odd
      if(i !== 0 && num[i-1]%2===1){// previous is odd either
        result+="-"+num[i];
      }else{
        result+=num[i];
      }
    }
  }
  return result;
}

console.log(StringChallenge([4,5,4,6,7,9,3]));

Try this :)

function test(a){
  let result=""

  for(let i=0; i < a.length; i++){
    if(a[i] != 0 && a[i-1] % 2 == 0 && a[i] % 2 == 0){
      result = result + '*' + a[i]
    }

    else if (a[i] != 0 && a[i-1] % 2 != 0 && a[i] % 2 != 0){
      result = result  + '-' + a[i]
    }
    else{
      result  = result + a[i]
    }
  }
  return result
}

console.log(test([4,5,4,6,7,9,3]));

As everyone has identified, the problem is you are not adding to result.

But here is a suggestion to make your code easier to read

// These one line functions make your code easier to read
function IsEven(num){
    return num % 2 === 0;
}

function IsOdd(num){
    return num % 2 !== 0;
}

function StringChallenge(numArray) {
    
    // return empty string if not an array or empty array
    if(!Array.isArray(numArray) || numArray.length === 0) return "";

    let result = "" + numArray[0];          // use "" to coerce first element of numArray from number to string

    for (let i = 1; i < numArray.length; i++) {
        
        // focus on the conditions to determine the separator you want between each element
        separator = "";

        if (numArray[i] !== 0) {
            
            if (IsEven(numArray[i]) && IsEven(numArray[i - 1])) {
                separator = "*";

            } else if (IsOdd(numArray[i]) && IsOdd(numArray[i - 1])){
                separator = "-";
            }
        }

        // build the result
        result += separator + numArray[i];
        
    }
    return result;
}

I will do that this way :

== some advices for 2 cents ==
1 - try to make your code as readable as possible.
2 - use boolean tests rather than calculations to simply do a parity test
3 - ES7 has greatly improved the writing of JS code, so take advantage of it

console.log(StringChallenge([4,5,4,6,7,9,3])); //  454*67-9-3

function StringChallenge( Nums = [] )
  {
  const 
    isOdd  = x => !!(x & 1)            // Boolean test on binary value
  , isEven = x => !(x & 1) && x!==0   // zero is not accepted as Even value 
    ;
  let result = `${Nums[0]??''}`;     // get first number as
                                    // result if Nums.length > 0
  for (let i=1; i<Nums.length; i++)
    {
    if ( isOdd(Nums[i-1])  && isOdd(Nums[i])  ) result += '-';
    if ( isEven(Nums[i-1]) && isEven(Nums[i]) ) result += '*';

    result += `${Nums[i]}`;        // same as Nums[i].toString(10);
    }
  return result
  }

I hope this helps. I tried to keep it as simple as possible.

function StringChallenge(num) {
//start with a string to concatenate, or else interpreter tries to do math 
operations
    let result = num[0].toString(); 
      function checkOdd(num){                      //helper function to check if odd 
          return num % 2
      }
    for (let i = 0; i < num.length - 1; i++) {                   
        if (checkOdd(num[i]) && checkOdd(num[i+1])) {           //checks if both odd
            result += `-${num[i+1]}`;                           //adds - and next number
        } else if (!checkOdd(num[i]) && !checkOdd(num[i+1])) {  //checks if both even
            result += `*${num[i+1]}`;                          //adds * and next number
        } else {                                                //otherwise
             result += num[i+1];                                //just add next number
        }
    }
    return result;
}
console.log(StringChallenge([4,5,4,6,7,9,3]));

Use +=. And, change your logic, your code prints out "4*67-99-3".

The zero check was pretty hard for me I hope the variables in my code explain itself. If not, let me know.

function even(num) {
    return num % 2 === 0;
}

function odd(num) {
  return num % 2 !== 0;
}

function StringChallenge(num) {
  let result = "";
  for (let i = 0; i < num.length; i++) {
    
    var currentZero = num[i] === 0
    var previousZero = num[i-1] === 0
    
    var bothEven = even(num[i]) && even(num[i-1])
    var bothOdd = odd(num[i]) && odd(num[i-1])
    var firstNumber = (i === 0)
        
    if (!currentZero) {
      if (firstNumber) {
        result += num[i]
      } else {
        if (bothEven && !previousZero) {
          result += "*" + num[i]
        } else if (bothOdd && !currentZero) {
          result += "-" + num[i]
        } else {
          result += num[i]
        }
      }
    }
    }
  return result;
}
console.log(StringChallenge([0,4,5,0,4,6,7,9,3]));

Related