The code is very wrong and not close to what it asks even having basic errors in the code, so consider doing simpler exercises first while not mastering something so complex. And if the statement is the same it is very vague and fits interpretation, so if you use the code fixed on some online trial site and keep giving error is probably a problem of how the statement was passed.
For example only those who wrote this know what is "it has to be an array that will show the months when q has tested positive with their balances on the side" since arrays don’t show anything, they serve to store values, and it gets harder to know what it means next door. Nor is it easy to understand what the exact relation is, the text is very ambiguous. I gave my interpretation. If this is not enough the question is not clear and we have no way to solve the problem with what was posted.
If you have to generate one array new to return at the end of the function then have to create it starting empty, do not have to create several other arrays for this.
So what you should do is create a new element in that array every time the condition is set in execution, the condition is right but before it was adding a value instead of creating that new element.
The statement asks to assemble the months that are above 0 with the balance value. It is not clear what is this balance. I understand that it is the accumulation of the previous months. Then you have to add up the previous month used and the current value that is greater than 0. That’s why I controlled the position of the array new I am to know which is the previous position (variable j
).
I make an exception to the first element of array because there is no way to catch the previous helmet when there is no element.
function saldoDeMesesComLucro(umPeriodo) {
var somas = [];
for (var i = 0, j = 0; i < umPeriodo.length; i++) {
if (umPeriodo[i] > 0) {
somas.push(umPeriodo[i] + (j == 0 ? 0 : somas[j - 1]));
j++;
}
}
return somas;
}
console.log(saldoDeMesesComLucro([0, 1, 2, 0, 3, 4, 0, 5, 0, 0, 6]));
I put in the Github for future reference.
Reinforcement to catch better defined problems even for help that is really useful.
You cannot pass a constant in the function statement.
– Augusto Vasques
Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).
– Maniero