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.
>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);