tharindu
tharindu

Reputation: 523

Return an array of values obtained from calling reduce() of JS

I have a json array as follows

var arrayVal = [{id:"1",name:"A", sAge: 20, eAge:30},{id:"2",name:"B", sAge: 30, eAge:50},{id:"2",name:"B", sAge: 20, eAge:40},{id:"3",name:"C", Aage: 20, eAge:50},{id:"4",name:"D", sAge: 10, eAge:30}];

I want to take difference of sAge and eAge of each id and sum the final value if there are multiple diff values of same id. For that I have the following code

const ages = array.reduce((a, {id, sAge, eAge}) => (a[id] = (a[id] || 0) + eAge - sAge, a), {});

console.log(ages);

output of the above code snippet is as follows

{
  "1": 20,
  "2": 50,
  "3": 20,
  "4": 10
}

But If I want to obtain an array as follows after using reduce(), how can I achieve that?

[{id:"1",name:"A", hours:"20"},{id:"2",name:"B", hours:"50"},{id:"3",name:"C", hours:"20"},{id:"5",name:"D", hours:"10"}]

Upvotes: 0

Views: 34

Answers (1)

Sergio Rinaudo
Sergio Rinaudo

Reputation: 2363

The following does the job but I didn't obtain your expected values

var arrayVal = [{id:"1",name:"A", sAge: 20, eAge:30},{id:"2",name:"B", sAge: 30, eAge:50},{id:"2",name:"B", sAge: 20, eAge:40},{id:"3",name:"C", sAge: 20, eAge:50},{id:"5",name:"D", sAge: 10, eAge:30}];

const ages = Object.values(arrayVal.reduce((a, {id, name, sAge, eAge}) => { 
  let difference = eAge - sAge;
  if(a.hasOwnProperty(id)) {
    a[id].hours+= difference;
  } else {
    a[id] = {
      id:id,
      name:name, 
      hours:difference
    }
  }
  return a;
}, {}));

Output

[
  {
    "id": "1",
    "name": "A",
    "hours": 10
  },
  {
    "id": "2",
    "name": "B",
    "hours": 40
  },
  {
    "id": "3",
    "name": "C",
    "hours": 30
  },
  {
    "id": "5",
    "name": "D",
    "hours": 20
  }
]

Upvotes: 2

Related Questions