Skip to main content
Became Hot Network Question
Tweeted twitter.com/StackCodeReview/status/1570064851992563712
Summarise the purpose, not the mechanism, in the title
Link
Toby Speight
  • 81.8k
  • 14
  • 101
  • 309

filter map reduce on checkboxes to calculate Calculate sum of values from checkboxes

Source Link

filter map reduce on checkboxes to calculate sum

I have a bunch of checkboxes with a data-amount attribute containing a value (positive or negative).

My goal is to generate a running total as the user checks each box, and then output this later on.

My code works - just curious for feedback as using filter, map and reduce seems overkill for something like this.

Thanks

const checkboxes = document.querySelectorAll('input[type=checkbox]');      
const output = document.querySelector('.runningTotal');

checkboxes.forEach(function(checkbox) {
        checkbox.addEventListener('change', function() {
            const runningTotal =
                Array.from(checkboxes) 
                .filter(i => i.checked) // remove unchecked checkboxes.
                .map(i => i.dataset.amount ??= 0) //extract the amount, or 0
                .reduce((total, item) => { return total + parseFloat(item)}, 0)
                
            console.log(runningTotal)
            output.innerHTML = runningTotal;
            
        })
    });
<input type="checkbox" data-amount="100"> 100
<input type="checkbox" data-amount="150"> 150
<input type="checkbox" data-amount="-50">  -50
<input type="checkbox" data-amount="10.50"> 10.50
<input type="checkbox" data-amount="0"> 0

<div class="runningTotal"></div>