help with the split

Asked

Viewed 44 times

-2

Good afternoon, I am trying to modify a script that I am creating to create a simple web page, the beginning of the code I was able to create, however I have difficulties in separating the result, like: in the code I created Oce inserted a value and returns 52 different results, and with that I want to separate from in blocks, it would be a total of 13 blocks, the first contains the result from 1 to 4, the second from 5 to 8 and so on, but besides that I want to add the result, and I am not getting, I searched on the internet for options and I arrived at the split, however I cannot fit into the script I am creating, below follows the code.

var plan = prompt("Valor depositado.");
for (var i =1; i<=52; i++){
    console.log(`${i} = ${i*plan}`);
}

1 answer

1


I don’t understand the point of this. Maybe you’re trying to solve a simpler problem but decided to ask how to do it the way you imagined, which would not be ideal.

To store the results 4 in 4, you can use the operator %, the module, which gives you the result of the division. If the result is 0, the number is divisible by 4, and you start to fill another block.

var plan = 10;
var blocos = [];
var resultados = [];

for (var i = 1; i <= 52; i++) {
    resultados.push(plan * i);
    if (i % 4 === 0) {
        blocos.push(resultados);
        resultados = [];
    }
}

var somaResultados = blocos.map(resultados => resultados.reduce((a, b) => a + b));
var somaBloco = somaResultados.reduce((a, b) => a + b);

console.log('blocos', blocos);
console.log('somaResultados', somaResultados);
console.log('somaBloco', somaBloco);

Now to add up the results, you can use the reduce method. Just provide a function callback and return the sum of the accumulated result (a) to the next item (b).

  • The idea in this code is to try to "replicate" the 52-week spreadsheet, the 13 blocks would be the months (remembering that it would have a 13°month that n has in the calendar), the separation would be more for the sake of organization, and the sum would be the value that would be given from the beginning each week.. But the way you did it already gave me a light, I’m still learning I tried to replicate this spreadsheet just as exercise to learn faster.

Browser other questions tagged

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