skip to Main Content

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


  1. You can use a map to maintain name to id map like:

    let map = {};
    products.forEach((product, index)=>{
      if(map.hasOwnProperty(product.productName)){
        products[index]['productId'] = map[product.productName];
      } else {
        map[product.productName] = products[index]['productId'];
      }
    })
    Login or Signup to reply.
  2. 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

    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 },
    ];
    
    function assignProductIds(products) {
      const productIdMap = {};
      let nextProductId = 1;
    
      return products.map((product) => {
        const { productName } = product;
    
        if (!productIdMap[productName]) {
          productIdMap[productName] = nextProductId;
          nextProductId++;
        }
    
        return { ...product, productId: productIdMap[productName] };
      });
    }
    
    const updatedProducts = assignProductIds(products);
    
    console.log(updatedProducts);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search