Advertisement
elena1234

How to use map and sort by value - JavaScript

Aug 27th, 2021
1,307
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.     let products = new Map();
  3.  
  4.     input.forEach(row => {
  5.         let [town, product, priceText] = row.split(' | ');
  6.         let price = Number(priceText);
  7.  
  8.         if (!products.get(product)) {
  9.             products.set(product, new Map());
  10.         }
  11.  
  12.         products.get(product).set(town, price);
  13.     })
  14.  
  15.  
  16.     let result = [];
  17.     for (const productWithValueTownPrices of products) {
  18.         let towns = [...productWithValueTownPrices[1]]; // spread into new area
  19.         let firstTownWithPrice = towns.sort((a, b) => a[1] - b[1]) [0]; // take first town after sorted by price
  20.         result.push(`${productWithValueTownPrices[0]} -> ${firstTownWithPrice[1]} (${firstTownWithPrice[0]})`); // print 'product -> price (town)'
  21.     }
  22.  
  23.     console.log(result.join('\n'));
  24. }
  25.  
  26. solve(['Sample Town | Sample Product | 1000',
  27. 'Sample Town | Orange | 2',
  28. 'Sample Town | Peach | 1',
  29. 'Sofia | Orange | 3',
  30. 'Sofia | Peach | 2',
  31. 'New York | Sample Product | 1000.1',
  32. 'New York | Burger | 10'
  33. ]
  34. )
  35.  
  36.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement