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

Time:09-18

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]));

CodePudding user response:

You do not need to check as if&continue. Adding characters to result and adding "-" only when index and previous is odd gives the requested result.

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

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

CodePudding user response:

Use =

There's another error in your logic. The code below print out "4*67-99-3"


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]));
  • Related