I'm a bit stuck merging objects (in this case 'adverts') within an array that have a matching property advertGroupId. For the matching properties, I would like to retain the earliest startDate and overwrite the endDate with the latest. Essentially, grouping the adverts together. (A bonus would be to also group the individual advertId's into an array too, but not essential in this case)
I'm aware of how to merge two objects together (eg. const newObj = {...obj1, ...obj2}), but this has me a bit stumped! I can't find any other examples online, so any help would be appreciated.
Here is an example of my problem:
const arrayOfAdverts = [
{
advertId: 1234,
startDate: '2020-03-04',
endDate: '2020-03-04',
advertGroupId: 1
},
{
advertId: 1235,
startDate: '2020-03-05',
endDate: '2020-03-05',
advertGroupId: 1
},
{
advertId: 1236,
startDate: '2020-03-07',
endDate: '2020-03-07',
advertGroupId: 1
},
{
advertId: 1237,
startDate: '2020-03-10',
endDate: '2020-03-10',
advertGroupId: 2
},
{
advertId: 1238,
startDate: '2020-03-11',
endDate: '2020-03-11',
advertGroupId: 2
}
]
I'm looking for an end result that would be:
const newArray = [
{
advertId: [1234, 1235, 1236],
startDate: '2020-03-04',
endDate: '2020-03-07',
advertGroupId: 1
},
{
advertId: [1237, 1238],
startDate: '2020-03-10',
endDate: '2020-03-11',
advertGroupId: 2
}
]
As I say, grouping the individual ID's isn't a requirement but would be a nice-to-have.
Thanks in advance!