Home > Blockchain >  Reactjs : how to reduce the array of objects to get the sum
Reactjs : how to reduce the array of objects to get the sum

Time:12-26

I have the array of objects and I want to group by description with the sum of credit. I tried with my code, but it doesn't work. What's wrong with it?

My Code:

var result1=[]
   entries.reduce((res, value) => {
       if (!res[value.description]) {
           res[value.description] = {description: value.description, credit: 0}
           result1.push(res[value.description])
       }
       
       res[value.description].credit= (parseFloat(value.credit)  
       parseFloat(res[value.description].credit)).toFixed(2)
      
       return res
      
   }, {});


   let analysisByDescStr = result1.map((str) => (
        <div>
            {str.description|| ""} =
            {str.credit|| ""}
        </div>
    ));

Array pf objects:

{description: 'GOOGLE *Google', credit: '1.99', category: 'TELECOM'}
{description: 'AMZN Mktp #0998', credit: '20.65', category: 'MERCHANDISE'}
{description: 'AMZN Mktp #06778', credit: '70.68', category: 'MERCHANDISE'}
{description: 'OLIVE YOUNG', credit: '60.03', category: 'MERCHANDISE'}
{description: 'SAFEWAY #0982', credit: '22.97', category: 'GROCERY'}
{description: 'PEET'S #11702', credit: '7.05', category: 'COFFEE'}
{description: 'SAFEWAY #0983', credit: '20.00', category: 'GROCERY'}
{description: 'AMZN Mktp #0234', credit: '-18.62', category: 'MERCHANDISE'}

My Expected Result :

AMZN Mktp=72.71
GOOGLE *Google=1.99
OLIVE YOUNG=60.03
PEET'S=7.05
SAFEWAY=42.97

CodePudding user response:

use reduce function

const list = [{description: 'GOOGLE *Google', credit: '1.99', category: 'TELECOM'},
{description: 'AMZN Mktp', credit: '20.65', category: 'MERCHANDISE'},
{description: 'AMZN Mktp', credit: '70.68', category: 'MERCHANDISE'},
{description: 'OLIVE YOUNG', credit: '60.03', category: 'MERCHANDISE'},
{description: 'SAFEWAY #0982', credit: '22.97', category: 'GROCERY'},
{description: 'PEETS #11702', credit: '7.05', category: 'COFFEE'},
{description: 'SAFEWAY #0983', credit: '20.00', category: 'GROCERY'},
{description: 'AMZN Mktp', credit: '-18.62', category: 'MERCHANDISE'}]

const result = list.reduce((acc, item) => {
  
  if(acc[item.description]){
    acc[item.description]  = Number(item.credit)
  }else{
     acc[item.description] = Number(item.credit)
  }
  
  return acc
}, {})

console.log(result)

CodePudding user response:

You can use reduce and apply whatever transformation you need to your item.description to match your expected labels

const result = list.reduce((acc, item) => {
  const label = item.description.substring(0, 7);
  return {
    ...acc,
    [label]: (acc.label ?? 0)   Number(item.credit)
  }
}, {})
  • Related