Front-end Tutorials

Front-end Tutorials

HTMLCSSSassJavaScriptReactJS
CMS Tutorials

CMS Tutorials

WordPress
Tutorials expand

Lodash _.sumBy() Math Method

Posted in lodash Tutorial
Updated on Oct 30, 2024
By Mari Selvan
👁️ 76 - Views
⏳ 4 mins
💬 1 Comment
Lodash _.sumBy() Math Method

Photo Credit to CodeToFun

🙋 Introduction

Efficiently handling numerical data is a common requirement in JavaScript programming. Lodash, a powerful utility library, provides a variety of functions to streamline array manipulation, and one such gem is the _.sumBy() method.

This method simplifies the process of calculating the sum of a specific property in an array of objects, making it an invaluable tool for developers dealing with datasets.

🧠 Understanding _.sumBy() Method

The _.sumBy() method in Lodash is designed for summing the values of a specific property in an array of objects. This can be particularly useful when working with datasets where you need to aggregate numerical values based on a common attribute.

💡 Syntax

The syntax for the _.sumBy() method is straightforward:

syntax.js
Copied
Copy To Clipboard
_.sumBy(collection, [iteratee=_.identity])
  • collection: The collection to iterate over.
  • iteratee (Optional): The function invoked per iteration.

📝 Example

Let's dive into a simple example to illustrate the usage of the _.sumBy() method:

example.js
Copied
Copy To Clipboard
const _ = require('lodash');

const expenses = [
  { category: 'utilities', amount: 100 },
  { category: 'groceries', amount: 150 },
  { category: 'utilities', amount: 80 },
];

const totalUtilitiesExpense = _.sumBy(expenses, 'amount');

console.log(totalUtilitiesExpense);
// Output: 180

In this example, the expenses array is processed by _.sumBy() to calculate the total sum of the 'amount' property.

🏆 Best Practices

When working with the _.sumBy() method, consider the following best practices:

  1. Validate Input Data:

    Before applying _.sumBy(), ensure that the input data is valid and contains the expected properties. This helps prevent unexpected results or errors.

    example.js
    Copied
    Copy To Clipboard
    const invalidData = [
      { item: 'apple', price: 1 },
      { item: 'banana' }, // Missing 'price' property
      { item: 'orange', price: 2 },
    ];
    
    const totalInvalidData = _.sumBy(invalidData, 'price');
    console.log(totalInvalidData);
    // Output: NaN (due to missing 'price' property)
  2. Provide a Default Value for Missing Properties:

    To handle cases where the specified property is missing in some objects, provide a default value or handle such scenarios gracefully.

    example.js
    Copied
    Copy To Clipboard
    const dataWithMissingProperties = [
      { product: 'laptop', price: 1200 },
      { product: 'mouse' }, // Missing 'price' property
      { product: 'keyboard', price: 50 },
    ];
    
    const totalWithDefault = _.sumBy(dataWithMissingProperties, obj => obj.price || 0);
    console.log(totalWithDefault);
    // Output: 1250
  3. Utilize Custom Iteratee Function:

    Use the iteratee parameter to apply a custom function for extracting values from each object. This allows for more complex calculations based on specific criteria.

    example.js
    Copied
    Copy To Clipboard
    const salesData = [
      { product: 'phone', revenue: 800, unitsSold: 2 },
      { product: 'tablet', revenue: 500, unitsSold: 1 },
      { product: 'laptop', revenue: 1200, unitsSold: 3 },
    ];
    
    const totalRevenue = _.sumBy(salesData, obj => obj.revenue * obj.unitsSold);
    console.log(totalRevenue);
    // Output: 4400

📚 Use Cases

  1. Total Expenses Calculation:

    _.sumBy() is particularly useful when you need to calculate the total sum of a specific property, such as 'amount' in a collection of expenses.

    example.js
    Copied
    Copy To Clipboard
    const expenses = [
      { category: 'utilities', amount: 100 },
      { category: 'groceries', amount: 150 },
      { category: 'utilities', amount: 80 },
    ];
    
    const totalUtilitiesExpense = _.sumBy(expenses, 'amount');
    console.log(totalUtilitiesExpense);
    // Output: 180
  2. Sales Revenue Aggregation:

    In scenarios where you have data on sales with revenue and units sold, _.sumBy() can be employed to calculate the total revenue by multiplying these values.

    example.js
    Copied
    Copy To Clipboard
    const salesData = [
      { product: 'phone', revenue: 800, unitsSold: 2 },
      { product: 'tablet', revenue: 500, unitsSold: 1 },
      { product: 'laptop', revenue: 1200, unitsSold: 3 },
    ];
    
    const totalRevenue = _.sumBy(salesData, obj => obj.revenue * obj.unitsSold);
    console.log(totalRevenue);
    // Output: 4400
  3. Statistical Analysis:

    For datasets requiring statistical analysis, _.sumBy() can be part of a broader set of calculations to derive insights from numerical properties.

    example.js
    Copied
    Copy To Clipboard
    const dataForAnalysis = /* ...fetch numerical data... */;
    
    const total = _.sumBy(dataForAnalysis, 'value');
    console.log(total);

🎉 Conclusion

The _.sumBy() method in Lodash provides a straightforward and efficient solution for calculating the sum of a specific property in an array of objects. Whether you're managing expenses, sales data, or conducting statistical analysis, this method empowers developers to perform numerical aggregations with ease.

By adhering to best practices and exploring diverse use cases, you can harness the full potential of the _.sumBy() method in your Lodash projects.

👨‍💻 Join our Community:

To get interesting news and instant updates on Front-End, Back-End, CMS and other Frameworks. Please Join the Telegram Channel:

Author

author
👋 Hey, I'm Mari Selvan

For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.

Buy me a coffee to make codetofun.com free for everyone.

Buy me a Coffee

Share Your Findings to All

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
We make use of cookies to improve our user experience. By using this website, you agree with our Cookies Policy
AgreeCookie Policy