Javascript - Separate a string and then add the values

Asked

Viewed 684 times

0

I’m starting in javascript and came across a question. I need the user to enter their date of birth, which I will store day, month and year in several different. What I need is to separate the values of these variables and then make a sum with them.

For example, the user inserts that the year of birth is 1994, so I need my program to do 1 + 9 + 9 + 4 = 23, which will be stored in the year variable.

Thank you!

  • Hi Lucas, what have you tried? Could you update your question with relevant code?

  • You already have something implemented so that we can work with it ? The field that the user will put will be text, date ? Please put more information to make the scenario a little clearer, because depending on the answers the solution can change

  • I’m on the phone right now and I can’t access what I was trying to post right now. But the field the user places is stored as a string, with a validation as to whether the format is correct: day and month with two digits and year with four.

  • What is the goal of adding up each digit of the year ? How will you get the year back after this calculation ?

  • Oi Issac, in each stage of the program he reduces (sum of digits) the highest value, from right to left, between day, month and year, until the sum of these is less than or equal to 22 and finally he associates this number with a "luck".

2 answers

1

Almost like:

var str = "1 + 4 + 5";
str = str.repalce(" ",""); //remove os espaços
str = str.split("+"); //transforma a str em array (lista)
for (i=0; i<str.length; i++){ //percorre a lista
    str[i] = parseInt(str[i]); //transforma os valores em inteiros
}

Now you will have a list of integers. Code for list sum:

function soma(lista){
    var total = 0;
    for (i=0; i<lista.length; i++){
        total += lista[i];
    }
    return total;
}

Perform like this:

soma(str);

1

Another way out is to use the reduce:

'1994'.split('').reduce((sum, x) => parseInt(x) + parseInt(sum)) // 23

Browser other questions tagged

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