Sum an Array of Numbers with JavaScript
It's rare that I'm disappointed by the JavaScript language not having a function that I need. One such case was summing an array of numbers -- I was expecting Math.sum
or a likewise, baked in API. Fear not -- summing an array of numbers is easy using Array.prototype.reduce
!
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((a, b) => a + b, 0);
The 0
represents the starting value while with a
and b
, one represents the running total with the other representing the value to be added. You'll also note that using reduce
prevents side effects! I'd still prefer something like Math.sum(...numbers)
but a simple reduce
will do!
Two years ago I documented my struggles with Imposter Syndrome and the response was immense. I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions. I've even caught myself reading the post...
Before we get started, it's worth me spending a brief moment introducing myself to you. My name is Mark (or @integralist if Twitter happens to be your communication tool of choice) and I currently work for BBC News in London England as a principal engineer/tech...
I've been working with the Magento eCommerce solution a lot lately and I've taken a liking to a technique they use with the top bar within their administrative control panel. When the user scrolls below a specified threshold, the top bar becomes attached to the...
One thing I love about love about Safari on the iPhone is that Safari provides a darkened background effect when you click a link. It's the most subtle of details but just enforces than an action is taking place. So why not implement that...
Initializing with 0 might not be necessary since it takes the value from the first item in the array if not provided (and then skips the first item for the rest). It’s very slightly slower to set it to 0.
Here’s what I wonder though… Suppose this were in some
math.js
module. Would it besum(nums)
orsum(...nums)
?sum([1,2,3])
orsum(1,2,3)
? I kinda prefer the latter.