Data wrangling: Sum values from two different arrays in javascript and push a new object

I have two arrays/json files in the following format:

  const data2 = [{date: "2018-04-23", a: 2, b: 2},
   {date: "2020-04-24", a: 1, b: 2},
   {date: "2020-04-25", a: 1, b: 2}]
  
  const data3 = [{date: "2018-04-23", a: 5, b: 2},
   {date: "2020-04-24", a: 4, b: 2},
   {date: "2020-04-25", a: 1, b: 2}]

and I want to get the following result:

  const result = [{date: "2018-04-23", sum: 7},
   {date: "2020-04-24", sum: 5},
   {date: "2020-04-25", sum: 1}]

what is the best way to calculate/create this new array?

I have tried this:

  let result = [];

  for( var i=1; i < data3.length; i++) {
    result.push({ date: data3[i].date,
                  sum: data2[i].a + data3[i].a})   
  }

The issue is that I need to make sure that both data2 and data3 arrays are sorted by date. Is there a better way to do it accounting for the date in the for loop? Any other structure different to a for loop is fine. I would like to know what is the best way to obtain the result array checking by date.

26 thoughts on “Data wrangling: Sum values from two different arrays in javascript and push a new object”

Leave a Comment