Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

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: 2}]

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.

question from:https://stackoverflow.com/questions/65948024/data-wrangling-sum-values-from-two-different-arrays-in-javascript-and-push-a-ne

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
const result = data2.map(item => {
    const fItem = data3.find(e=>e.date === item.date)
    if(fItem){
        return {date: item.date, sum: item.a + fItem.a}
    }
    return {date: item.date, sum: item.a}
})

I hope this code will useful for you

And I have the other solution is to convert data3 as an object with keys are date and values are an attribute. For example:

const object = data3.reduce((init, item)=> ({...init, [item.date]: item.a}), {})

After that use is the same above

    const fItem = data3.find(e=>e.date === item.date)

change to

    const fItem = obj[item.date]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...