1

I have this object

[
      {
            "year": 2020,
            "term": 1,
            "worthAmountEGP": 0
      },
      {
            "year": 2020,
            "term": 2,
            "worthAmountEGP": 300000
      },
      {
            "year": 2021,
            "term": 1,
            "worthAmountEGP": 0
      },
      {
            "year": 2021,
            "term": 2,
            "worthAmountEGP": 1000000
      },
      {
            "year": 2021,
            "term": 1,
            "worthAmountEGP": 0
      },
      {
            "year": 2021,
            "term": 2,
            "worthAmountEGP": 400000
      },
      {
            "year": 2022,
            "term": 1,
            "worthAmountEGP": 0
      },
      {
            "year": 2022,
            "term": 2,
            "worthAmountEGP": 1000000
      }
]

I have been trying to sum the worthAmountEGP based on multiple conditions (same year and same term )

this is what I have been trying

const transformed = Object.values(
      aa.reduce((acc, { term, worthAmountEGP, year }) => {
            acc[term] = acc[term] || { term, worthAmountEGP: 0 };
            acc[term].worthAmountEGP += worthAmountEGP;
            return acc;
      }, {})
);

this is my output

Transformed: [
  { term: 1, worthAmountEGP: 5000000 },
  { term: 2, worthAmountEGP: 3200000 },
]

my desired output is

[
  { term: 1, worthAmountEGP: 0, year:2020 },
  { term: 2, worthAmountEGP: 300000, year:2020 },
  { term: 1, worthAmountEGP: 0, year:2021},
  { term: 2, worthAmountEGP: 1400000, year:2021},
  { term: 1, worthAmountEGP: 0, year:2022},
  { term: 2, worthAmountEGP: 1000000, year:2022},
]

1 Answer 1

2

Reduce the array to a Map (acc). Create a key by combining the year and the term. If the Map doesn't have the key, set a copy of the current object. If it does exist, add to the current value of worthAmountEGP. Get an array by using Array.from() on the Map's .values() iterator:

const data = [{"year":2020,"term":1,"worthAmountEGP":0},{"year":2020,"term":2,"worthAmountEGP":300000},{"year":2021,"term":1,"worthAmountEGP":0},{"year":2021,"term":2,"worthAmountEGP":1000000},{"year":2021,"term":1,"worthAmountEGP":0},{"year":2021,"term":2,"worthAmountEGP":400000},{"year":2022,"term":1,"worthAmountEGP":0},{"year":2022,"term":2,"worthAmountEGP":1000000}]

const result = Array.from(data.reduce(
  (acc, o) => {
    const key = `${o.year}---${o.term}`
    
    if(!acc.has(key)) acc.set(key, { ...o })
    else acc.get(key).worthAmountEGP += o.worthAmountEGP
    
    return acc    
  }, new Map()
).values())

console.log(result)

Not the answer you're looking for? Browse other questions tagged or ask your own question.