-1

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.

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.

  • 3
    What happens if both duplicates have a `sku` value? Keep the last value? The highest value (treating the value as a number)? etc – DBS Nov 14 '22 at 14:30
  • @DBS if there are 2 overlapping sizes then there will always be 1 object with `sku = null` – Dang Khoa Duong Nov 14 '22 at 14:33

1 Answers1

0

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: '36 ⅔', sku: '11'},
  {size: '36 ⅔', sku: null},
  {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 acc; // if (acc[item.size] && acc[item.size].sku) return acc;
  // record the item by size
  acc[item.size] = item;
  return acc;
}, {}));

console.log(result);
epascarello
  • 204,599
  • 20
  • 195
  • 236