We have an array of objects with keys productid and productname. productnames are duplicate but productid is unique. Assign same productid to all duplicate products in this array of objects in javascript
expected input:
const products = [
{ productId: 1, productName: 'Apple', price: 1.0 },
{ productId: 2, productName: 'Banana', price: 0.5 },
{ productId: 3, productName: 'Orange', price: 1.2 },
{ productId: 4, productName: 'Apple', price: 1.0 },
{ productId: 5, productName: 'Banana', price: 0.5 },
];
expected output:
const products = [
{ productId: 1, productName: 'Apple', price: 1.0 },
{ productId: 2, productName: 'Banana', price: 0.5 },
{ productId: 3, productName: 'Orange', price: 1.2 },
{ productId: 1, productName: 'Apple', price: 1.0 },
{ productId: 2, productName: 'Banana', price: 0.5 },
];
2
Answers
You can use a map to maintain name to id map like:
You can create a mapping of unique product names to their corresponding product IDs. Then, iterate through the array, and for each object, assign the product ID based on the mapping