title: Algorithm to solve stores and products minimum total price
body: <p>I have a JSON array of products with nested array of stores that supply them:</p>
  
  <pre><code>let arrayOfProducts =
   [
    {
      "title": "ProductA",
      "stores": [
        {
          "name": "Store1",
          "price": 15.09
        },
        {
          "name": "Store2",
          "price": 16.30,
        },
        {
          "name": "Store4",
          "price": 16.55,
        },
        .
        .
        .
        "title": "ProductB",
        "stores": [
          {
            "name": "Store1",
            "price": 8.06
          },
          {
            "name": "Store3",
            "price": 9.25,
          },
          {
            "name": "Store4",
            "price": 9.27,
            },
          .
          .
          .
      ]
  </code></pre>
  
  <p>I need to find the combination of the minimum number of store(s)(due to extra shipping constraint) that provide all of the products at the lowest TOTAL price.</p>
  
  <p>e.g. lets say the array has five products ProductA-ProductE.There is no single store in their respective arrays that can supply all of them. Store2 supplies a subset of the products and so does any other store. </p>
  
  <p>The output should be like that:</p>
  
  <pre><code>[
  {
      "name": "store1",
      "price": total_price_for_this_store,
      "products": [ "ProductC"]
  },
  {
      "name": "store2",
      "price": total_price_for_this_store,
      "products": [ "ProductA", "ProductB", "ProductD"]
  },
  {
      "name": "store3",
      "price": total_price_for_this_store,
      "products": [ "ProductE"]
  }
  ]
  </code></pre>
  
  <p>I have managed to create the expected output using javascipt's forEach and filter functions, but only to find the solution if one or more stores have ALL the products and not a subset of them.</p>
  
  <pre><code>let results = []
  arrayOfProducts.forEach((product) =&gt; {
    product.stores.forEach(store =&gt; {
      let storeIndex = results.findIndex(el =&gt; { return el.name === store.name })
      if (storeIndex === -1) { // first occurence of the shop in the array of results
        results.push({
          name: store.name,
          price: store.price,
          products : [product.title]
        })
      } else {
        results[storeIndex].price += store.price
        results[storeIndex].products.push(product.title)
      }
    })
  })
  
  let allProducts = results.filter((store) =&gt; {
    return store.products.length === arrayOfProducts.length
  })
  
  allProducts.sort(function (a, b) {
    return parseFloat(a.price) - parseFloat(b.price)
  })
  </code></pre>
  
  <p>How can i approach this problem?I dont know how to start.</p>
  
  <p>Does it belong to the LP category of algorithms?</p>