Scroll an array and insert values in the middle of it

0

I need to create a program in JS that receives a requirment of user digits (ex: 11223655871) and returns the sequence with '-' between even numbers and '#' between odd numbers, ie the result will be: 1 # 12-2365 # 587 # 1

    
asked by anonymous 03.11.2018 / 15:10

3 answers

2

var num=11223655871;
var result="";

var digits = num.toString().split('');

var realDigits = digits.map(Number);

for(i = 0; i < realDigits.length; i++)
{
    var value1 = realDigits[i];
    var value2 = realDigits[i+1];
    
    result += value1;
    
    if(value1 % 2 != 0 && value2 % 2 != 0) {
        result += "#";
    }else if(value1 % 2 == 0 && value2 % 2 == 0){
        result += "-";
    }
}

result = result.substring(0,(result.length - 1));

console.log(result);

Concepts:

  • The toString () method returns a string representing the object
  • The split () method divides a String object into an array of strings by separating the string into substrings
  • The map () method creates a new array with the results of calling a function for each element of the array.
03.11.2018 / 16:11
0

You can use the Array.prototype.reduce function, observe the last character of the first argument and the second argument, see if they are the even / odd, and return the number with potentially the symbol in the middle.

    
03.11.2018 / 15:59
0

I think regular expression is the best way to format your string.

let meuNum = 11223655871;
let numFormatdo = '${meuNum}'.replace(/([13579])([13579])/g, '$1#$2')
                             .replace(/([02468])([02468])/g, '$1-$2');
                            
console.log(numFormatdo);
    
03.11.2018 / 16:11