I am getting data from an api and displaying it in a table with 2 columns. 1st column contains the name and the second column contains amount as shown in Table1. The data in the api contains duplicate names and amounts are different for the same name. I wanted to display in such a way that it sums up the amount for the unique name and displays only unique names and the total amount as shown in Table2. I am using ReactJS for displaying the table. What is a better logic to get this result. I am retrieving data from api as json and getting it into an array. I am pretty new to React and is finding it difficult to play with the data.
The core problem is not really a problem related to react, so, considering I cannot influence the API, we can solve the aggregation in javascript. One helpful library to do so is "lodash" - it knows how to do a classic "reduce" and knows how to make an array from an object. Solving this on the node console, we get:
npm install lodash
node
>
...
const ld = require("lodash");
a = [{n: "joe", d: 1},{n: "joe", d: 1}, {n: "joe", d: 3} ]
b = ld.reduce(a, (agg, {n,d}) => { agg[n] = (agg[n] || 0) + d; return agg; }, {});
ld.map(b, (val,prop) => ({ n: prop, d: val});
The return value of the last line gives you
[ { n: 'joe', d: 5 } ]