using the .reduce() method | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

using the .reduce() method

I'm trying to use the reduce method on the numbersToSum array (bottom of the code), but it doesn't seem to work. I'm a beginner with javascript and i've never used this method, can someone help? let displayField = document.querySelector('input'); let digit = document.querySelector('.digit'); let numbersDigit = document.querySelector('.number-btn'); let operations = document.querySelector('.operation-btn'); let numbersToSum = []; displayField.value = ''; //digit numbers in display digit.addEventListener('click', (e) => { if(e.target.className === 'number-btn'){ displayField.value += e.target.innerHTML; } //storing numbers in the array if(e.target.className === 'sum-btn'){ numbersToSum.push(parseInt(displayField.value)); displayField.value = ''; console.log(numbersToSum); //summing the numbers if(e.target.className === 'result-btn'){ numbersToSum.reduce((total, num)=>{ return total + num; }); console.log(numbersToSum) } } })

19th Mar 2020, 8:33 PM
Francesco Paolini
Francesco Paolini - avatar
4 Answers
+ 3
You are using .reduce correctly but you need to store the result somewhere. let result = numbersToSum.reduce((a, b) => a + b); console.log(result);
19th Mar 2020, 8:40 PM
Schindlabua
Schindlabua - avatar
+ 1
Sorry but it doesn't seem to work. It doesn't log the variable even if I write it like this: if(e.target.className === 'result-btn'){ let storingSum = numbersToSum.reduce((total, num)=>{ return total + num }); console.log(storingSum); }
20th Mar 2020, 10:02 AM
Francesco Paolini
Francesco Paolini - avatar
+ 1
Oh it was just a dumb syntax error, I was putting the third if statement inside the second one! Thank you for your attention Schindlabua!
20th Mar 2020, 11:40 AM
Francesco Paolini
Francesco Paolini - avatar
0
That probably implies that `e.target.className !== 'result-btn'` and you never land in the if-block at all. You can try uploading your code to the code playground and we can have a look if you want!
20th Mar 2020, 10:04 AM
Schindlabua
Schindlabua - avatar