I have an array of objects
const data = [{
productId: 7000254,
quantity: 1
}, {
productId: 7000255,
quantity: 1
}, {
productId: 7000256,
quantity: 1
}, {
productId: 7000257,
quantity: 1
}, {
productId: 7000254,
quantity: 1
}];
I need to get unique values from it using the reduce function.
I made it using below code
data.map((rp) => {
if (products.map(({ productId }) => productId).indexOf(rp.productId) === -1) {
products.push({ productId: parseInt(rp.productId), quantity: 1 })
}
})
but as you can see it's a lengthy process because I have to iterate over the array multiple times. So is there any way using reduce function?
var unique = data.reduce((a, b ,c,d) => {
if (a.map(({productId}) => productId).indexOf(b.productId) === -1) {
return [a,b]
}
})
console.log(unique)
Expected output
0: {productId: 7000254, quantity: 1}
1: {productId: 7000255, quantity: 1}
2: {productId: 7000256, quantity: 1}
3: {productId: 7000257, quantity: 1}