4 ms·
There's already `Array.prototype.reduce()` in most browsers, which will do summing, string concatenation, and any other kind of aggregation: https://developer.
by guscost 11y ago
There's already `Array.prototype.reduce()` in most browsers, which will do summing, string concatenation, and any other kind of aggregation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
If you need something more convenient I highly recommend just adding lodash and getting a whole bag of rock-solid awesome tools.
- astrange 11y agoreduce isn't a safe way to add floating-point numbers unless your accumulator is much more precise than your array values. You'll end up with what they call "catastrophic cancellation". And they won't let you have fixed-point in JavaScript!
- guscost 11y agoDoesn't a for loop have the same problem?
- astrange 11y agoIf you write the loop yourself, you can add everything to a double instead of a float, or a long double instead of a double, if you have those. Oh, if all your numbers are positive you can also sort the array and it will minimize the error accumulated, but I'm not sure what to do with mixed signs.