how to use the sumby function from lodash in javascript

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.tsx
const lodash = require('lodash');

const countries = [
  { name: 'USA', population: 328.2 },
  { name: 'China', population: 1386 },
  { name: 'India', population: 1380 },
  { name: 'Brazil', population: 210 },
  { name: 'Pakistan', population: 220 }
];

const totalPopulation = lodash.sumBy(countries, country => country.population);

console.log(totalPopulation); // Output: 4134.2
383 chars
14 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