Utilize Lodash to group by ID and calculate the sum in order to assign the new sum value

Is it possible to use Lodash to sort and group by a specific key (such as "id") and update the values of the elements by adding all unique values of another key (e.g. payout)?
For example, can we take the array below:

[
  {
     id: 1,
     payout: 15,
     numOfPeople: 4
  },
  {
     id: 1,
     payout: 12,
     numOfPeople: 3
  },
  {
     id: 2,
     payout: 6,
     numOfPeople: 5
  },
  {
     id: 2,
     payout: 10,
     numOfPeople: 1
  }
]

... and transform it into the following using LODASH:

  // Note how the payout values have been summed up for each id group

[
  {
     id: 1,
     payout: 27,
     numOfPeople: 4
  },
  {
     id: 1,
     payout: 27,
     numOfPeople: 3
  },
  {
     id: 2,
     payout: 16,
     numOfPeople: 5
  },
  {
     id: 2,
     payout: 16,
     numOfPeople: 1
   }
 ]

Answer №1

To achieve this, you can utilize a combination of filter, map, and reduce.

const data = [
  {
    id: 1,
    payout: 15,
    numOfPeople: 4,
  },
  {
    id: 1,
    payout: 12,
    numOfPeople: 3,
  },
  {
    id: 2,
    payout: 6,
    numOfPeople: 5,
  },
  {
    id: 2,
    payout: 10,
    numOfPeople: 1,
  },
];

const idPayoutMap = {};

let finalResult = data.map(item => {
  if (idPayoutMap['' + item.id] !== undefined) {
    item.payout = idPayoutMap['' + item.id];
  } else {
    item.payout = data
      .filter(elem => elem.id === item.id)
      .reduce((total, elem) => elem.payout + total, 0);
    idPayoutMap['' + item.id] = item.payout;
  }

  return item;
});


console.log(finalResult);

Check out a working demo here

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

Is there a method to access the variable name of v-model from a child component in the parent component?

In the scenario below, I am customizing a vue radio component and using the model option to retrieve the v-model value, which is expected to be a string '1'. Is there a way for me to access its variable name 'radio1' in the child compon ...

What is the reason for having the navigation bar stretch across the entire width of the mobile device?

NEW QUESTION: How Can I Fix the Navigation Bar Issue on Mobile Devices? I apologize for any language issues as I am using a translator. Hello, I have encountered an issue with a website form containing a price list. When viewed on a mobile device, all the ...

Obtain information from an ajax request

I am working on a website where I need to implement a button that checks if the user has specific permissions before opening a new web page in a popup window. In my JavaScript code, I have the following function: function sendAjax(methodName, dataArray, s ...

Node.js API requests often result in undefined responses

As a newcomer to Node.JS, I am currently experimenting with calling a REST API using the GET method. I have utilized the 'request' package available at this link. While the call functions correctly, I encounter an issue when attempting to return ...

Utilizing jQuery and JSON to showcase the contents of an array

My goal is to display all the items in an array by utilizing JSON and jQuery from the Song of Ice and Fire API. Currently, I am only able to display one item from each of the arrays. If you want to view the codepen, click here: https://codepen.io/frederic ...

Is it possible to validate only the fields that are currently visible using HTML form validation

I need a solution for excluding hidden fields from HTML form validation. My situation involves having two groups of form fields, each with some required attributes. Depending on user selection, one group may be hidden, and those fields should not contribut ...

Modifying the status using retrieved JSON information

My goal is to retrieve data from an external API and use it to update the state of my app. Although I can see the data in the console, the state of my app remains unchanged when I try to run setState. class App extends Component { state={ jobs:[] ...

Hide Material UI Drawer when clicking elsewhere

Attempting to implement the Drawer component in Material UI React. Want to ensure that the state within the Drawer component persists even when the Drawer is closed, so passing variant="persistent" in Drawer component. The issue arises with the ...

I seem to be having trouble locating the correct file location

Apologies for the simplicity of my question. I've been struggling to include the find.js file in my articles.js file. Despite trying multiple variations, I can't seem to get the pathname right and haven't found a solution online. Can someon ...

The retrieved item has not been linked to the React state

After successfully fetching data on an object, I am attempting to assign it to the state variable movie. However, when I log it to the console, it shows as undefined. import React, {useState, useEffect} from "react"; import Topbar from '../H ...

How can I prevent the arrow keys and space bar from causing my webpage to shift downwards?

I created a game where the arrow keys control movement and the space bar shoots, but every time I press the down key or space bar, it scrolls to the bottom of the web page. Is there a way to adjust the CSS so that it focuses on the game div tag without ...

The output of new Date() varies between app.js and ejs

app.get("/test",function(req,res){ var d = new Date(); res.send(d); }); When I access mydomain/test, it displays the output "2019-03-19T04:50:47.710Z" which is in UTC. app.get("/testejs",function(req,res){ res.render("testejs");}); Below is the content ...

What is the proper way to parse an array of JSON objects?

Here is the data I need help with: var information = [ { "_id": "5e458e2ccf9b1326f11b5079", "xxTitle": "testtttttttttttt", "hhhhhhhhhh": "sssssssss", "xxzzzzzz": null, "oooooooooooooo": "ssssss", "xxDescription": "sssssss", "xxDetails": "ssssssss", "llll. ...

Executing an external HTTP request within an ExpressJS middleware prior to rendering the response

Currently, I am facing a challenge while trying to utilize Express middleware for a login request. The default route generates an external URL that redirects to /login?code={login-code}. This URL triggers an external HTTP request to obtain the user_id and ...

Struggling with implementing the use of XMLHttpRequest to transfer a blob data from MySQL to JavaScript

I have a blob stored in my local WAMP64/MySQL server that I need to retrieve and pass to an HTML file using XMLHttpRequest. I know I should set responseType="blob", but I'm not sure how to transfer the blob from PHP to JavaScript in my HTML file. Any ...

Are the files selected by the user not displaying properly in the URL?

I'm currently working on a project using PhoneGap where I am facing an issue with uploading files and adding all file names to the parameters. The desired format is: http://www.example.com/uplaod.html?file=file1,file2,file3 To achieve this, I have a ...

Activate a dropdown menu following the selection of a date on a calendar input using vue.js

What I need to do is have two select fields, one for 'days' and the other for 'hours'. When a day is selected, the user should then be able to choose between two available time slots. If they choose day two, the available time slots sh ...

Exploring jQuery: Choosing all li elements starting from a specific index to the end

Is there a way to select the last item, li:eq('+(lastItemIndex)+')', and all subsequent items until the end? Check out this JSFiddle demo for an example of changing elements in li from 3 onwards. ...

Iterate through an array of objects and add them to a fresh array

I am encountering an issue where I would like to generate a fresh array of objects in order to avoid utilizing a nested array map. However, the error message below is being displayed: TypeError: Cannot read property 'subscriber_data' of undefine ...

Exploring the challenging surfaces of a mesh through raycasting in Three.js

I successfully built a box using three.js var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera( 100, window.innerWidth/window.innerHeight, 0.1, 1000 ); camera.position.set(5, 5, 10); var geo = new THREE.BoxGeometry(5,2,5); var mat = n ...