Traverse an array and insert values in the middle of it

Asked

Viewed 187 times

0

I need to create a JS program that takes a user’s digit frequency (eg 11223655871) and returns the sequence with '-' between even numbers and '#' between odd numbers, that is, the result will be: 1#12-2365#587#1

  • The result would not be 1#1#2-2-3#6-5#5#8-7#1# or there is another condition not explained in the question?

  • No, '-' is only inserted between even numbers and '#' between odd numbers. Between an even number and an odd number no value is entered.

  • understood, between TWO even numbers and between TWO odd numbers

3 answers

1


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 matrix with the call results of a function for each matrix element.

0

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

0

I believe 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.