Advertisement
Lulunga

Associative Arrays 06. Travel Time

Jul 6th, 2019
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function travelTime(input) {
  2.     let countries = {};
  3.  
  4.     input.forEach(line => {
  5.         let [country, town, price] = line.split(' > ');
  6.         price = Number(price);
  7.         if (!countries.hasOwnProperty(country)) {
  8.             countries[country] = {};
  9.             countries[country][town] = price;
  10.         } else {
  11.             let existingCountryObj = countries[country];
  12.             if (!existingCountryObj.hasOwnProperty(town)) {
  13.                 countries[country][town] = price;
  14.             } else {
  15.                 let oldPrice = countries[country][town];
  16.                 price = Math.min(oldPrice, price);
  17.                 countries[country][town] = price;
  18.             }
  19.         }
  20.     });
  21.     let sorted = Object.entries(countries).sort((firstPair, secondPair) => {
  22.         let [firstCountry, firstData] = firstPair;
  23.         let [secondCountry, secondData] = secondPair;
  24.         return firstCountry.localeCompare(secondCountry);
  25.     });
  26.     for (let [name, towns] of sorted) {
  27.         let sortedTowns = Object.entries(towns).sort((firstTown, secondTown) => {
  28.             let firstPrice = firstTown[1];
  29.             let secondPrice = secondTown[1];
  30.             return firstPrice - secondPrice;
  31.         });
  32.         let output = `${name} -> `;
  33.         for (let townName in towns) {
  34.             let townPrice = towns[townName];
  35.             output += `${townName} -> ${townPrice} `;
  36.         }
  37.         console.log(output);
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement