Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-2024-08-06· OpenAIAi2 WildChat-4.8M (AI2)

lodash aggreate sum

  1. User

    lodash aggreate sum

  2. Assistant

    In Lodash, you can use the _.sumBy function to aggregate the sum of values in an array of objects based on a specific property. The _.sumBy function iterates through each element in the collection and returns the sum of results after applying a function to each element, typically to access a specific property. Here's how you can use it:

    Assume you have an array of objects and you want to sum up the values of a specific property:

    const _ = require('lodash');
    
    const items = [
      { name: 'Item 1', quantity: 10 },
      { name: 'Item 2', quantity: 5 },
      { name: 'Item 3', quantity: 15 }
    ];
    
    const totalQuantity = _.sumBy(items, 'quantity');
    
    console.log(totalQuantity); // Output: 30
    

    In this example, _.sumBy is used to sum up all the quantity values in the items array. If you need to sum based on a more complex logic or computation, you can also pass a function as the second argument:

    const totalQuantity = _.sumBy(items, item => item.quantity);
    

    This achieves the same result and is useful if you need to perform additional calculations or transformations on each item before summing.