Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
215 views
Welcome To Ask or Share your Answers For Others

1 Answer

Reduce the array down to an object with name as the key and the collected items as the values ,then run a map on the keys of the object to return the required array.

const obj = orders.reduce((map, order) => {
const { name } = order;
if (map[name]) {
  map[name].push(order.item);
} else {
  map[name] = [order.item];
}
return map}, {})
const output = Object.keys(obj).map(key => ({name:key,item:obj[key]}))
console.log(output)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...