0

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: []
  }
]
0

2 Answers 2

3

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks that did work, I was trying to figure this out for educational reasons though with reduce because it's bothering me like crazy I can't get it to work
1

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)

7 Comments

hey thanks a lot, I just tried this, it is almost working. If you look at my expected output it's not quite working though the way I expect.
This is not what OP wants...
Changed my code now
@Pratik Wadekar Super close, the only thing is the linked_products should be pointing only to other products with the same title property. Here they point to themselves
Your input contains no test a but the output does. How come ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.