I have an array of orders below and would like to condense it by name and then have an array of all the items that person has ordered
const orders = [
{ name: 'Tedd', item: 'coke', },
{ name: 'Louise', item: 'burger' },
{ name: 'Louise', item: 'chips' },
{ name: 'David', item: 'chips' },
{ name: 'David', item: 'burger' },
{ name: 'David', item: 'coke' }
]
how i want it to look
[
{ name: 'Tedd', item: ['coke'] },
{ name: 'Louise', item: ['burger', 'chips'] },
{ name: 'David', item: ['chips', 'burger', 'coke'] }
]
I tried this
const out = [...new Set(orders.map(i => i.name))].map(i => {
return { name: i, item: orders.reduce((a, b) => [a.item].concat([b.item])) }
})
but it just concatenates all the orders
[
{ name: 'Tedd', item: ['chips', 'burger', 'coke'] },
{ name: 'Louise', item: ['chips', 'burger', 'coke'] },
{ name: 'David', item: ['chips', 'burger', 'coke'] }
]
question from:https://stackoverflow.com/questions/66067556/how-to-condense-an-array-of-objects