Given an array of objects, containing products. A single object contains a single product offer. Products can have a identical productId, while offerId are unique for each product.
Process the data to get the cheapest priced item for each offer
const data = [
{ productId: 'dhdiwu', offerId: 'd3en', price: '$12.20' },
{ productId: 'dhdiwu', offerId: 's2dr', price: '$8.45' },
{ productId: 'dhdiwu', offerId: 'hy38', price: '$21.21' },
{ productId: 'dowksm', offerId: 'ie8u', price: '$1.77' },
{ productId: 'dowksm', offerId: 'djs3', price: '$24.21' },
{ productId: 'dowksm', offerId: 'pies', price: '$92.36' },
{ productId: 'bdbhsu', offerId: '9wid', price: '$100.98' }
]
const dataArray = data.reduce((prev, t, index, arr) => {
if (typeof prev[t.productId] === 'undefined') {
prev[t.productId] = [];
}
prev[t.productId].push(t);
return prev;
}, {});
let same_id = []
let cheapest = []
Object.keys(dataArray).forEach(i => {
same_id.push(dataArray[i]);
});
console.log(same_id)
//output for now
/*[
[
{ productId: 'dhdiwu', offerId: 'd3en', price: '$12.20' },
{ productId: 'dhdiwu', offerId: 's2dr', price: '$8.45' },
{ productId: 'dhdiwu', offerId: 'hy38', price: '$21.21' }
],
[
{ productId: 'dowksm', offerId: 'ie8u', price: '$1.77' },
{ productId: 'dowksm', offerId: 'djs3', price: '$24.21' },
{ productId: 'dowksm', offerId: 'pies', price: '$92.36' }
],
[ { productId: 'bdbhsu', offerId: '9wid', price: '$100.98' } ]
]*/