0

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"}]

1 Answer 1

2

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
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.