What is the best way to perform a deep sumBy operation with lodash?

var data= [{
        "item_name": "Jumbo Combo",
        "item_key": "9lazhy15tp2fgo72",
        "item_price": 25,
        "quantity": 1,
        "ingredients": [{
            "group_key": "fg1udvnz81qwpxtp",
            "key": "kcck54k7h3fzp5f0",
            "ingredient_name": "Large",
            "price": 3
        }]
    }, {
        "item_name": "Swiss & Mushroom Combo",
        "item_key": "e1vdfos6s50d5kej",
        "item_price": 22,
        "quantity": 1,
        "dependencies": [{
            "group_key": "fg1udvnz81qwpxtp",
            "key": "kcck54k7h3fzp5f0",
            "name": "Large",
            "price": 3
        }]
    }]

i am interested in calculating the total cost of each item, including both the item_price and the prices of any additional ingredients. I would like to achieve this using lodash's method sumBy.

I initially attempted to calculate just the sum of item_price:

_.sumBy(data, 'item_price')

This successfully calculates the total price of all items in the array based on their item_price. However, I need to find a way to include the sum of both the ingredients and the item_price.

Answer №1

Calculating Total Costs with Lodash

Instead of simply summing the values of certain attributes in an array using the _sumBy function, it is also possible to define a custom function that specifies how to derive the individual values for summation. For example:

_.sumBy(data, <b>x => x.item_price</b>)

But what if we need to include the costs of ingredients as well? In such cases, we can nest another _.sumBy function for the ingredients:

_.sumBy(data, x => x.item_price + <b>_.sumBy(x.ingredients, 'price')</b>)

(resulting in a total cost of 53).

Incorporating Quantity Into Calculation

To factor in the quantity attribute as well, we can multiply each item's total cost by its respective quantity:

_.sumBy(data, x => <b>x.quantity * (</b>x.item_price + _.sumBy(x.ingredients, 'price')<b>)</b>)

(again giving us a final cost of 53, assuming uniform quantities of 1 for all items).

Answer №2

When using Lodash#SumBy, you have the option to pass a function as the second argument. This allows you to access the ingredients of each item and apply SumBy once again.

const data = [{ item_name: 'Jumbo Combo', item_price: 25, item_key: '9lazhy15tp2fgo72', quantity: 1, ingredients: [{ group_key: 'fg1udvnz81qwpxtp', key: 'kcck54k7h3fzp5f0', ingredient_name: 'Large', price: 3 }]}, { item_name: 'Swiss & Mushroom Combo', item_key: 'e1vdfos6s50d5kej', item_price: 22, quantity: 1, ingredients: [{ group_key: 'fg1udvnz81qwpxtp', key: 'kcck54k7h3fzp5f0', ingredient_name: 'Large', price: 3 }]}];

const sum = _.sumBy(data, item => item.item_price + _.sumBy(item.ingredients, 'price'));

console.log(sum);
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bad6d5dedbc9d2fa8e948b8d948e">[email protected]</a>/lodash.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving the selected date from JqueryUI Datepicker after form submission

I am currently using an inline datepicker that fills in an input textbox. $("#left-calendar").datepicker({ altField: "#left-date-text" }); The left-date-text is located within a form, and upon submission with a submit button, it sends the data to a p ...

Determine the scrolling progress within a DOM element

My application requires content to be loaded as the user scrolls down, similar to social media platforms like Twitter and Facebook. I am currently working on detecting the need to load more data based on scroll events and the current position of the scrol ...

Enhance Page Content Dynamically with Symfony2 and Ajax-Like Functionality

When assessing an ArrayCollection in my Template, I am currently using the following loop: {% for article in articles %} <li {% if article.new %} class="new" {% endif %} >{{ article.name|e }}</li> {% endfor %} My go ...

What is an elegant way to showcase a large 2D array in a WPF application, similar to the layout of Excel spreadsheet

Currently, I'm facing a challenge involving the display of a 2-dimensional array within a WPF window. The size of the array can reach up to 360*720 dimensions. Attempting to use a DataTable bound to a DataGrid proved to be inefficient, as it resulted ...

Issue with Ionic 2's infinite scroll not triggering method on second scroll attempt

I utilized the ion-tab element to showcase a page (inboxitem) which encompasses ion-list and makes use of ion-infinite-scroll. The following code snippet resides in inboxitem.html <ion-content class="inbox can-swipe-list"> <ion-list> ...

Determine the overall width of a JSX element

Is there a way to retrieve the width of a JSX.Element? In a traditional setup, I would typically use something like: const button = document.createElement('button'); document.body.appendChild(button) window.getComputedStyle(button).width However ...

Streamline your processes by automating jQuery AJAX forms

I am looking to automate a click function using the code snippet below in order to directly submit form votes. Is there a method to develop a standalone script that can submit the votes without requiring a webpage refresh: <input type="submit" id="edit ...

What is the method for breaking down a React useState hook into separate variables within a namespace?

Personally, I like to group React props into namespaces for better organization. When using the useState hook, I follow this approach. function MyComponent() { const [todoCount, setTodoCount] = useState(100); const [doneCount, setDoneCount] = useSta ...

Error: The function $(...).froalaEditor is not recognized | This issue is occurring within the $(document).ready(function(){}) block in J

When attempting to set HTML content of the Froala editor within a JSP using $(document).ready(), this error occurs. TypeError: $(...).froalaEditor is not a function | $(document).ready(function(){}) in JSP I read on a GitHub issue that placing jQuery sc ...

The issue of javascript Map not updating its state is causing a problem

I've encountered an issue where my components are not re-rendering with the updated state when using a map to store state. const storage = (set, get) => ({ items: new Map(), addItem: (key, item) => { set((state) => state.items ...

Transitioning from SJAX to AJAX

I am in the process of updating a portion of my script to use AJAX instead of Synchronous JAX to prevent the page from freezing. My goal is to check if a password is valid before sending it to the server. If the password is not valid, I want the password f ...

Issue with hide.bs.modal event not triggering in Bootstrap 3.2 when using Django 1.6.5 with remote modal content

I need help with a dashboard I'm working on that displays a list of hosts. When a user clicks on a host, I want to show additional details in a modal dialog. Right now, I am using Bootstrap's remote modal feature to trigger a Django view and popu ...

Refreshing a node in Jqgrid Treegrid by updating the local source data

I have constructed a Treegrid using local data $("#historyGrid").jqGrid({ datatype: "jsonstring", datastr : treeGridObject , colNames:["Id","Channel","Current","History","Delta"], colModel:[ {name:'id', index:'Id&apo ...

Failure to deliver messages through socket.emit

Check out the following JavaScript code snippet: `var express = require('express'); var app = express(); var http = require('http').Server(app); var path = require("path"); var io = require('socket.io')(http); app.get(&apos ...

retrieving the value of an object key based on changing information

console.log(x, obj.fares) //return undefined output adultFare Object {adultFare: "9.00", childFare: null, seniorCitizenFare: null, disabledFare: null,} How do I retrieve the adultFare value from the object? Is looping through the keys necessary? I expec ...

What is the syntax for implementing a for loop/for each loop in EJS?

I'm trying to figure out how to include this code snippet inside <% %>. I'm not sure if it's similar to a typical forEach/for loop. The documentation on EJS site is quite limited, so I've turned to this forum for help. <% incl ...

Discovering the overall number of rows stored within a database

I've been reading through various topics on retrieving row numbers but I'm having trouble grasping the concepts. All I really need is a simple way to get the total number of rows. Currently, I have this code that reads each row and fills up a li ...

ASP.NET sending an AJAX request

Hi, I am new to the world of ajax requests and asp.net. I am facing an issue while sending an ajax request to an aspx page. Even though the server side debugging seems fine, I am encountering an error message in the response. I have already tried changing ...

Is it possible for me to modify the text in the address bar without leaving the current page?

My client asked me to create a search page, but the challenge is that the actual search functionality is within an iframe, and the user sees a decorative shell around it. The shell passes URL parameters to the iframe, which processes them and carries out t ...

When using the setTimeout function, jQuery's .submit() method may fail to pass data to PHP

I'm attempting to enhance the login form with an effect that triggers a 1-second delay before proceeding to PHP. I tried implementing a setTimeout() function within the .submit event handler along with e.preventDefault() to create the delay, but enco ...