Un merging of Javascript array data

Solution 1:

Here is a version using reduce and spread. You will have to convert to typescript yourself

Note I need to deep clone the objects so I use JSON.parse(JSON.stringify)

const input = [ { "type": "COLLECTION", "address": "Address A", "goods": [ "Pepsi" ], "datetime": "2022-01-02T12:00:00.000Z" }, { "type": "COLLECTION", "address": "Address B", "goods": [ "Pizza" ], "datetime": "2022-01-02T13:00:00.000Z" }, { "type": "COLLECTION", "address": "Address C", "goods": [ "Burger" ], "datetime": "2022-01-02T14:00:00.000Z" }, { "type": "DELIVERY", "address": "Address Z", "goods": [ "Pepsi", "Pizza", "Burger" ], "datetime": "2022-01-03T08:00:00.000Z" }, { "type": "COLLECTION", "address": "Address D", "goods": [ "Maggi" ], "datetime": "2022-01-03T09:00:00.000Z" }, { "type": "DELIVERY", "address": "Address D1", "goods": [ "Maggi" ], "datetime": "2022-01-03T10:00:00.000Z" }, { "type": "COLLECTION", "address": "Address E", "goods": [ "Cheese", "Egg", "Butter" ], "datetime": "2022-01-03T08:00:00.000Z" }, { "type": "DELIVERY", "address": "Address E1", "goods": [ "Cheese" ], "datetime": "2022-01-03T12:00:00.000Z" }, { "type": "DELIVERY", "address": "Address F1", "goods": [ "Egg" ], "datetime": "2022-01-03T13:00:00.000Z" }, { "type": "DELIVERY", "address": "Address G1", "goods": [ "Butter" ], "datetime": "2022-01-03T14:00:00.000Z" }, ];

// create a keyed delivery table - I assume one key to one collected item
const deliveries = input.filter(({type}) => type==="DELIVERY").reduce((acc,cur) => {
  cur.goods.forEach(item => {
    acc[item] = JSON.parse(JSON.stringify(cur))
    acc[item].goods = [item]
  })
  return acc
},{})

output = Object.entries(deliveries).reduce((acc,entry) => {
  const [key,value] = entry
  const inp = input.filter(({goods}) => goods.includes(key))[0]
  acc.push(JSON.parse(JSON.stringify(inp)))
  acc.push({...deliveries[key],goods:[key]})
  return acc
},[])

console.log(output)