简体   繁体   中英

Using reduce to group array of objects

I am having a crazy hard time figuring this out, maybe because I almost never use the reduce method and I have been looking at this way too long but all I am trying to do here is group together an array of objects based on the product title.

const products = [
    {
        id: 1,
        title: 't-shirt'
    },
    {
        id: 2,
        title: 't-shirt'
    },
    {
        id: 3,
        title: 'jeans'
    }
]

const linked_products = products.reduce((prevProduct, product) => {
    
}, [])

products.forEach(product => {
  // this is an array of objects
  // it's an array of objects with the same title
  product.linked_products = linked_products
})

Expected Output:

products = [
  {
    id: 1,
    title: 't-shirt',
    // here is the new property
    linked_products: [
      { id: 2, title: 't-shirt'}
    ]
  },
  {
    id: 2,
    title: 't-shirt',
    linked_products: [
      { id: 1, title: 't-shirt'}
    ]
  },
  {
    id: 3,
    title: 'jeans',
    linked_products: []
  }
]

Does it have to be with reduce?

A forEach would fit your need pretty well:

 const products = [ { id: 1, title: 't-shirt' }, { id: 2, title: 't-shirt' }, { id: 3, title: 'jeans' } ] products.forEach( item => { item.linked_products = products.filter( linked => linked.id != item.id && linked.title == item.title ).map(({id,title,...rest}) => ({id,title}) ) } ) console.log(products)

UPDATED CODE

 const products = [ { id: 1, title: 't-shirt' }, { id: 2, title: 't-shirt' }, { id: 3, title: 'jeans' } ] const mappedProducts = products.map(product => { const linkedProducts = products.filter(prod => prod.id !== product.id && prod.title === product.title); return { ...product, linkedProducts } }) console.log(mappedProducts)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM