Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove duplicate array object with condition

I have a array as below:

const data = [
{size: '36 ⅔', sku: '11'},
{size: '36 ⅔', sku: null},
{size: '44', sku: null},
{size: '45', sku: '112'},
]

I’m trying to find a way that can delete products that overlap in size.

In case there are 2 products with the same size, but the one with the sku and the other without sku, so the object with the sku should be kept.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If there are 2 object overlapping sizes then there will always be 1 object with sku = null

The sizes in the array only overlap once

I’ve spent hours working on this but still no desired result.

This is the result I want:

const data = [
{size: '36 ⅔', sku: '11'},
{size: '44', sku: null},
{size: '45', sku: '112'},
]

Someone please help me, Thanks.

>Solution :

Simple reduce loop checking if you have a size with a sku. If you do, leave it be, if you do not add a record.

const data = [
  {size: '43', sku: null},
  {size: '43', sku: '111'},
  {size: '44', sku: null},
  {size: '45', sku: '112'},
]

const result = Object.values(data.reduce((acc, item) => {
  // does the size have a sku already? then ignore it
  if (acc[item.size]?.sku) return; // if (acc[item.size] && acc[item.size].sku) return;
  // record the item by size
  acc[item.size] = item;
  return acc;
}, {}));

console.log(result);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading