Advertisement
simeonshopov

Lowest Prices

May 20th, 2021
817
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.   const products = [];
  3.   const cities = [];
  4.  
  5.   for (const info of input) {
  6.     let [town, product, price] = info.split(' | ');
  7.     price = Number(price);
  8.     if (!products.includes(product)) products.push(product);
  9.     const city = cities.filter(x => x.town == town)
  10.     if (city.length == 0) {
  11.       cities.push({town:town, [product]: price});
  12.     } else if (!Object.keys(city[0]).includes(product)) {
  13.       city[0][product] = price;
  14.     } else {
  15.       city[0][product] = price;
  16.     }
  17.   }
  18.  
  19.   for (const product of products) {
  20.     let lowersPriceTown = cities.filter(x => Object.keys(x).includes(product)).sort((a, b) => a[product] - b[product]);
  21.     (checkSamePrice(lowersPriceTown, product)) ? lowersPriceTown =  lowersPriceTown.sort((a, b) => cities.indexOf(a) - cities.indexOf(b))[0]
  22.     : lowersPriceTown = lowersPriceTown[0];
  23.     console.log(`${product} -> ${lowersPriceTown[product]} (${lowersPriceTown.town})`);
  24.   }
  25.  
  26.   function checkSamePrice (arr, product) {
  27.     for (let i = 0; i < arr.length - 1; i++) {
  28.       if (arr[i][product] == arr[i + 1][product]) return true;
  29.     }
  30.     return false;
  31.   }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement