0

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!

2
  • 1
    As the dupe target is only for the grouping part, I've put together an example which fulfills all your requirements: jsfiddle.net/yek0pdf5 Commented Mar 16, 2020 at 17:23
  • @Andreas you, Sir, are a gentleman and a scholar. Exactly what I was looking for! Commented Mar 17, 2020 at 18:42

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.