Ivankooo1

Lowest Prices in Cities

Sep 26th, 2020 (edited)
165
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. function solve(arr){
  2. let obj = {};
  3.  
  4. for(let item of arr){
  5. let [townName,productName,productPrice] = item.split(" | ");
  6. productPrice = +productPrice;
  7.  
  8. if(!obj[productName]){
  9. obj[productName] = {};
  10. }
  11.  
  12. if(!obj[productName][townName]){
  13. obj[productName][townName] = productPrice;
  14. }else{
  15. obj[productPrice][townName] += productPrice;
  16. }
  17. }
  18.  
  19. let arrOfObj = Object.entries(obj);
  20.  
  21. arrOfObj.forEach(element => {
  22. let product = element[0];
  23. let resultPrices = Object.values(element[1]);
  24. let lowestPrice = Math.min(...resultPrices);
  25. let lowestTown = Object.keys(element[1])
  26. .filter(x => obj[product][x] === lowestPrice);
  27.  
  28. console.log(`${product} -> ${lowestPrice} (${lowestTown})`)
  29. });
  30. }
  31.  
  32. solve(
  33. ['Sample Town | Sample Product | 1000',
  34. 'Sample Town | Orange | 2',
  35. 'Sample Town | Peach | 1',
  36. 'Sofia | Orange | 3',
  37. 'Sofia | Peach | 2',
  38. 'New York | Sample Product | 1000.1',
  39. 'New York | Burger | 10']
  40. )
Advertisement
Add Comment
Please, Sign In to add comment