kstoyanov

05. Lowest Prices in Cities v3

Sep 29th, 2020
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function lowestPrice(input) {
  2.   const prices = {};
  3.  
  4.   for (const line of input) {
  5.     const [town, product, price] = line.split(' | ');
  6.  
  7.     if (!prices.hasOwnProperty(product)) {
  8.       prices[product] = [];
  9.       prices[product].push({ town, price: Number(price) });
  10.      
  11.     } else {
  12.       let hasTown = false;
  13.       for (const key in prices) {
  14.         if (key === product) {
  15.           for (const obj of prices[key]) {
  16.             hasTown = true;
  17.             if (obj.town == town) {
  18.               obj.price = Number(price);
  19.             } else if (obj.price > Number(price)) {
  20.               prices[key].push({ town, price: Number(price) });
  21.             }
  22.           }
  23.         }
  24.       }
  25.       if (!hasTown) {
  26.         prices[product].push({ town, price: Number(price) });
  27.       }
  28.     }
  29.   }
  30.   for (const key in prices) {
  31.     const sorted = Object.entries(prices[key]).sort((a, b) => a[1].price - b[1].price);
  32.     console.log(`${key} -> ${sorted[0][1].price} (${sorted[0][1].town})`);
  33.   }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment