In this post I was using lodash 4.17.10
So there are a number of methods in lodash that can be used to add up a sum, such as _.sum which can be used to quickly add up the numbers of an array. In addition summation can also easily be done with methods like _.reduce, and _.forEach. However in this post I will be focuising on methods like _.sum, and _.sumBy.
using the _.sum method is easy enough, just pass an array of numbers to it any you are done.
Although I most real world examples I can not say that I often deal with an array that is formated like this, I must first produce this array, or I must loop over an array of objects adding up one or more values and ignoring others. Not to worry there are other methods that can be used together to deal with most of those situations as well such as _.sumBy.
Say I have a not just an array of numbers, but an array of objects, and I need to make a sum by preforming an operation for each object. For example say I have an array of objects where each object is a report for sales and expenses for a certain business day. I want to add up how much profit has been made for each day, so I will need to subtract expenses from sales and then add that result up for each day. This can easlit be done with _.sumBy.
The _.reduce methods can be used to create a sum fairly quickly as well.
So if you are using the full lodash library then there are all the methods that lodash has to offer that can be used to help with the process of working out a more complicated task involving a sum. The lodash methods like groupBy can be used in conjunction with others like _.map with Implicit Chaining.
Say you have a bunch of objects that share a common value, and I want all objects that share that value summed up I could pull that off by doing something like this.
Noting wrong with just using a for a while loop that is what they are there for. When using a while loop there is the trick of setting an index value to the length of an array and then subtracting from the index variable that is also evaluated in the while loop. This works because the number zero evaluates to false.
For example I can use that to quickly make a method that will figure an average of an array of numbers like this.
Using a native method like Array.forEach can be useful for quickly adding up some numbers.