The sumBy
function from lodash
is used to find sum of a collection, where the values of each item in the collection are summed based on a specified property or function. Here's an example of using sumBy
:
index.tsx383 chars14 lines
In this example, we have an array of objects countries
, where each object represents a country and has a name
and population
property. We want to find the total population of all the countries, so we call lodash.sumBy()
on the countries
array and pass a callback function as the second argument. This callback function takes each element of the array as an argument and returns the population
property of that element.
lodash.sumBy()
then iterates over the array and applies the callback function to each element to extract the population
property of that element. The values of population
property are then summed to get the total population of all the countries.
The output of running this code would be 4134.2
, which represents the total population of all the countries in the array.
gistlibby LogSnag