Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
}
]Advertisements