kstoyanov

05. Lowest Prices in Cities v2

Sep 29th, 2020 (edited)
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.     let products = [];
  3.     input.forEach( el => {
  4.         let [town, product, price] = el.split('|').map(x => x.trim());
  5.         price = Number(price);
  6.  
  7.         let currentProduct = products.find(x => x.product === product);
  8.  
  9.         if (!currentProduct) {
  10.             products.push({
  11.                 product,
  12.                 offers: [{
  13.                     town,
  14.                     price
  15.                 }]
  16.             });
  17.             return;
  18.         }
  19.  
  20.         const currentTown  = currentProduct.offers.find(x => x.town === town);
  21.  
  22.         if (!currentTown) {
  23.             currentProduct.offers.push({
  24.                 town,
  25.                 price
  26.             });
  27.             return;
  28.         }
  29.         currentTown.price = price;
  30.     });
  31.  
  32.     products.forEach( el => {
  33.         const sortedTowns = el.offers.sort((a,b) => a.price - b.price);
  34.         const lowestOffer = sortedTowns[0];
  35.         console.log(`${el.product} -> ${lowestOffer.price} (${lowestOffer.town})`);
  36.     })
  37. }
Add Comment
Please, Sign In to add comment