Lodash sumByThe Lodash sumBy method allows you to add the values of the objects in your array, specifying the objet property that should be targeted.

In this article, you will learn about the Lodash sumBy method, and how it can be helpful in your website or application. These examples assume that you already know what Lodash is, and that you have it loaded in your project.

Often, you may find yourself working with large arrays filled with objects. Sometimes an object has a property that is a numerical value, and you may need to calculate a total of those values. You could use native JavaScript to get the total, but you would need to use a for-loop and introduce new variables into the scope of your project. Extra variables are never desirable, and using many for-loops causes a lot of duplicate code, which goes against the programmer’s DRY (Don’t Repeat Yourself) philosophy.

Lodash sumBy Syntax

_.sumBy(array, [iteratee=_.identity])

The Lodash sumBy method takes two arguments. The first argument is the array that holds the values. The second argument is the object property, or iteratee, that you want to sum.

Examples

Let’s take a look at a few examples that use the Lodash sumBy method to get a better handle on this feature.

Example 1

In Example 1, we can get a more precise look at how the syntax works. In this example, we have an array named cars that holds three objects. Each object has three parameters, name, cost, and issuv.

The sumBy method looks at the cars array and iterates through each element, summing the value of the cost parameter. When it’s finished, it assigns the total value to the constant totalCosts.

Example 2

In Example 2, we can start to really see the advantages of the Lodash sumBy method. In this example, we can sum the values of the objects that are truthy for issuv and skip the rest. This kind of math would likely require another function and for-loop in standard JavaScript, but with Lodash, we can accomplish it with a slight change to our code.

Example 3

In Example 3, we show you another way to use the Lodash sumBy method. This time we use the method to find the total of all cars that are higher than a specific value. You can do this math with only a slight change in code, and it uses far fewer lines than would be required if you tried to solve this problem using native JavaScript.

Conclusion

I hope that you have enjoyed reading over these Lodash sumBy examples and have learned something new. Using Lodash to solve problems like this can clean up your code and make it a lot easier to read. If you have a lot of this type of math to do on your website or application, the reduced lines of code can start to add up. Using Lodash also helps to keep your code DRY, which allows your code to move into the future.

Please share these Lodash sumBy examples on Facebook and Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *