Jenny
Jenny

Reputation: 494

Function in Javascript that inserts dashes or asterisks between each two odd or even numbers

I want to write a function that inserts dashes (' - ') between each two odd numbers and inserts asterisks (' * ') between each two even numbers. For instance:

Input: 99946
Output: 9-9-94*6

Input: 24877
Output: 2*4*87-7

My try


function dashAst (para) {

    let stringArray = para.toString().split('');

    let numbArray = stringArray.map(Number);
      


    for (let i = 0; i<numbArray.length; i++) {

      if (numbArray[i] %2 === 0 && numbArray[i+1] % 2 === 0) {
        numbArray.splice(numbArray.indexOf(numbArray[i]), 0, '*')
      } 
      
      else if (numbArray[i] %2 !== 0 && numbArray[i+1] %2 !== 0) {
        numbArray.splice(numbArray.indexOf(numbArray[i]), 0, '-')
      }
    }
    
    return numbArray
}

When I try to invoke the function it returns nothing. For instance, I tested the splice-command separately and it seems to be correct which makes it even more confusing to me. Thanks to everyone reading, or even helping a beginner out.

Upvotes: 0

Views: 1365

Answers (3)

sonEtLumiere
sonEtLumiere

Reputation: 4572

I hope this helps

var str = '24877';

function dashAst (para) {
  let stringArray = para.toString().split('');
  let numbArray = stringArray.map(x => parseInt(x));
  console.log(numbArray);
  var out=[];
      
  for(let i = 0; i < numbArray.length; i++) {
    if(numbArray[i] % 2 == 0){
      out.push(numbArray[i]);
      numbArray[i + 1] % 2 == 0 ? out.push('*') : 0;
    }else if(numbArray[i] % 2 != 0) {
      out.push(numbArray[i]);
      numbArray[i + 1] != undefined ? out.push('-') : 0;
    }
  }
  console.log(out.join(''));
  return out;
}

dashAst(str);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386868

You could map the values by checking if the item and next item have the same modulo and take a separator which is defined by the modulo.

function dashAst(value) {
    return [...value.toString()]
        .map((v, i, a) => v % 2 === a[i + 1] % 2 ? v + '*-'[v % 2] : v)
        .join('');
}

console.log(dashAst(99946)); // 9-9-94*6
console.log(dashAst(24877)); // 2*4*87-7

Upvotes: 2

blex
blex

Reputation: 25648

Looping through an Array that changes its length during the loop can be very messy (i needs to be adjusted every time you splice). It's easier to create a new result variable:

function dashAst(para) {
  const stringArray = para.toString().split('');
  const numbArray = stringArray.map(Number);
  let result = "";

  for (let i = 0; i < numbArray.length; i++) {
    const n = numbArray[i], next = numbArray[i + 1];
    result += n;
    if (n % 2 == next % 2) {
      result += n % 2 ? '-' : '*';
    }
  }

  return result;
}

console.log(dashAst(99946)); // "9-9-94*6"
console.log(dashAst(24877)); // "2*4*87-7"

Upvotes: 2

Related Questions