-2

Given the following Dates:

var b = [
    {Date:'Jan 2016', steel:10.98},
    {Date:'Feb 2016', steel:5.67},
    {Date:'Jan 2016', steel:3.14},
    {Date:'Feb 2016', steel:2.14},
    {Date:'Mar 2016', steel:12.14}
]

I want to calculate both sum and cumulative average with respect to the dates shown above.

My desired output is:

Sum ->

[{"Date": "Jan 2016","val": 14.12},
{"date": "Feb 2016","val": 7.81},
{"date": "Mar 2016","val": 12.14}]

Cumulative Average ->

[{"Date": "Jan 2016","val": 7.06 },
{"date": "Feb 2016","val": 5.48},
{"date": "Mar 2016","val": 6.814}]
Cristian Ramon-Cortes
  • 1,838
  • 1
  • 19
  • 32
  • Possible duplicate of [Merging array objects with same properies](https://stackoverflow.com/questions/48585817/merging-array-objects-with-same-properies) – Calvin Nunes Apr 18 '18 at 12:04
  • 2
    Please read [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – str Apr 18 '18 at 12:04
  • That's an array of objects, no [JSON](http://json.org) involved. – Andreas Apr 18 '18 at 12:19

1 Answers1

0

const sumSteelAndConcrete = (s = { steel: 0 }, c = { steel: 1 }) => s.steel + c.steel; const findByDate = (arr, date) => arr.find(item => item.Date === date);

const result = dates.map( sumSteelAndConcrete( findByDate(steelDays, date), findByDate(steelDays, date) ) ) );