Merge JSON array date based JavaScript


Suppose, we have the following array of objects −

const arr = [
   {
      "date" : "2010-01-01",
      "price" : 30
   },
   {
      "date" : "2010-02-01",
      "price" : 40
   },
   {
      "date" : "2010-03-01",
      "price" : 50
   },
   {
      "date" : "2010-01-01",
      "price2" : 45
   },
   {
      "date" : "2010-05-01",
      "price2" : 40
   },
   {
      "date" : "2010-10-01",
      "price2" : 50
   }
];

We are required to write a JavaScript function that takes in one such array. The function should then merge the objects based on the "date" property of objects.

Example

const arr = [
   {
      "date" : "2010-01-01", "price" : 30
   },
   {
      "date" : "2010-02-01",
      "price" : 40
   },
   {
      "date" : "2010-03-01",
      "price" : 50
   },
   {
      "date" : "2010-01-01",
      "price2" : 45
   }, {
         "date" : "2010-05-01",
         "price2" : 40
   },
   {
      "date" : "2010-10-01",
      "price2" : 50
   }
];
const mergeArray = (arr = []) => {
   const data = arr.slice();
   data.sort((a, b) => new Date(a.date) - new Date(b.date))
   const res = []
   data.forEach(el => {
      if(!this[el.date]) {
         this[el.date] = {
            date: el.date,
            price: null,
            price2: null
         }
         res.push(this[el.date])
      }
      this[el.date] = Object.assign(this[el.date], el)
   });
   return res;
}
console.log(JSON.stringify(mergeArray(arr), undefined, 4));

Output

And the output in the console will be −

[
   {
      "date": "2010-01-01",
      "price": 30,
      "price2": 45
   },
   {
      "date": "2010-02-01",
      "price": 40,
      "price2": null
   },
   {
      "date": "2010-03-01",
      "price": 50,
      "price2": null
   },
   {
      "date": "2010-05-01",
      "price": null,
      "price2": 40
   },
   {
      "date": "2010-10-01",
      "price": null,
      "price2": 50
   }
]

Updated on: 21-Nov-2020

542 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements