0

I have multiple objects of which I would like to concatenate their nested arrays based on an ID. For example:

data = [
        {roomId: 1,
         nights: [ "2022-05-06",
                   "2022-05-07"
                 ] 
        },

        {roomId: 2,
         nights: [ "2022-05-06",
                   "2022-05-07",
                   "2022-05-08"
                 ] 
        },

        {roomId: 1,
         nights: [ "2022-05-10",
                   "2022-05-11",
                   "2022-05-07",
                 ] 
        },

        {roomId: 2,
         nights: [ "2022-05-12",
                   "2022-05-13",
                   "2022-05-14"
                 ] 
         }
]

For each roomId I would like to create one nights array with all the dates (including duplicates). Ideally I would have a count for the frequency of each night in that array as well.

Desired Output

newObject = [
        {roomId: 1,
         nights: [ {date:"2022-05-06", count:1}
                   {date:"2022-05-07", count:2}
                   {date:"2022-05-10", count:1}
                   {date:"2022-05-11", count:1}
                 ] 
        },

        {roomId: 2,
         nights: [ {date:"2022-05-06",count:1}
                   {date:"2022-05-07",count:1}
                   {date:"2022-05-08",count:1}
                   {date:"2022-05-12",count:1}
                   {date:"2022-05-13",count:1}
                   {date:"2022-05-14",count:1}
                 ] 
        },
]

I have tried a couple map and reduce functions but have not been able to come up with anything that is producing the results I'm looking for. Any help is greatly appreciated!

isherwood
  • 58,414
  • 16
  • 114
  • 157
Code4fun
  • 21
  • 2
  • You are supposed to show what you tried, for 'helping hands', not asking for free code. please read https://stackoverflow.com/help/how-to-ask. did you also read this site quideline https://stackoverflow.com/tour – Mister Jojo Jul 27 '22 at 15:25
  • data.sort((a, b) => a.roomId - b.roomId).reduce((prev, current) => { console.log(prev, current) return !!prev && Array.isArray(prev) ? prev[prev.length - 1].roomId === current.roomId ? prev.map((item, index) => {return index === prev.length - 1 ? {...item, nights: [...item.nights, ...current.nights]} : item}) : [...prev, current] : prev.roomId === current.roomId ? [{...prev, nights: [...prev.nights, ...current.nights]}]: [prev, current] }) this work try a method to optimize the function – Pasquale De Lucia Jul 27 '22 at 15:51

0 Answers0