1

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.

enter image description here

Midhun Mathew Sunny
  • 1,271
  • 4
  • 17
  • 30
  • What code/logic do you have so far? – anbnyc May 25 '17 at 16:24
  • Do you have control over the API?, also, separate the problem into smaller steps. Try displaying the rows as they come. Try fetching the data and display it in the console. Aggregating the values is rather a javascript problem, not a react one. – flq May 25 '17 at 16:29
  • I am getting the data from the api, storing it in the state as an array(this.state.data) and i have the Table1 displayed. Now I want to get the the required data as in Table2 in a separate array. – Midhun Mathew Sunny May 25 '17 at 16:29
  • No, I don't have control over the api. I have displayed the data and got till Table1. Yes, I am stuck at aggregating the values. – Midhun Mathew Sunny May 25 '17 at 16:31

1 Answers1

2

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 } ]
flq
  • 22,247
  • 8
  • 55
  • 77
  • Could you also add the code to convert parameter 'd' in your json array 'a' from string to float. – Midhun Mathew Sunny May 25 '17 at 18:08
  • That is easily googleable, with a link probably into this very site – flq May 25 '17 at 18:52
  • I searched. What i wanted to do is to change the type of json object's parameter to float. I have used `var c = ld.map(a, (item) => {item.d= parseFloat(item.d); return item;}, {})` But it was returning me Nan – Midhun Mathew Sunny May 25 '17 at 18:59