0
`ForEach` only returns undefined and `map` and `reduce` do not work on this problem. How to make code work?!
My code needs to increase the elements in the salary by percent, calculate the accumulated salary in the funtion and return the total accumulated percents using the forEach Method in node js. https://code.sololearn.com/cp0F1jRsDnzc/?ref=app https://code.sololearn.com/cp0F1jRsDnzc/?ref=app
13 Antworten
0
forEach should be used like a for loop to iterate over a target array... this is why there's no return value (undefined).
from inside if the callback function, you could access outside variables (if they are in same scope than where the callback is created) as well as arguments (value, index, array)...
so, one (pseudo) code solution could be:
var r = 0;
salaries.forEach((v,i,a) => {
v *= percent/100;
a[i] += v, r += v;
});
console.log('accumulated percents: '+r);
console.log('salaries: ['+salaries+']');
0
It still doesnt work. All it says is v is undefined
0
sory, forgotten parenthesis around arguments (v,i,a): corrected ;)
0
Excuse me if im blind but what parenthesis were forgotton
0
I initially wrote:
forEach(v,i,a => {
Now that's corrected to:
forEach((v,i,a) => {
0
And when i run it it shows the accumulation for the first element then the array then the second element then the second array and so on
0
I just need one value from the array but it gives me more
0
I initially think to only write pseudo code, but I finally write real code...
however, you shouldn't expect to have only to copy a working solution, but use my example to wite your own solution (where I had already made most of the work)
0
When i console.log r it prints the values i need but need to reduce them into one number. Do you have any ideas on how i can do that
0
And it returns a fifth value thats undefined. Ima keep working on it but this problem is insane
0
Thanks for helping it not return undefined. Ill leep workin n hope to debug it
0
Hey ive still been working on the problem it returns the value i need but returns undefined on all my code at the end on the value. I think im supposed to do a callback for the code soIi only get the values but i dont know how to do that. heres my code
function main() {
var percent = parseInt(readLine(),10);
console.log(salaryIncrease(percent));
}
var salaries = [3000, 7000, 5000, 15000];
const salaryIncrease = percent => {
//your code goes here
var r = 0;
salaries.forEach((v,i,a) => {
v *= percent/100;
a[i] += v, r += v;
});
console.log(r);
}