Advertisement
VeselaVideva

Objects and Classes - Exercise - 09. Catalogue

Oct 23rd, 2020
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function solve(input) {
  2.     let catalogue = {};
  3.     const alphaSort = (a, b) => a.localeCompare(b);
  4.  
  5.     for (let line of input){
  6.         let [name, price] = line.split(" : ");
  7.         price = Number(price);
  8.         let initial = name[0];
  9.  
  10.         if (!catalogue.hasOwnProperty(initial)){
  11.             catalogue[initial] = {};
  12.         }
  13.  
  14.         let products = catalogue[initial]
  15.  
  16.         if (!products.hasOwnProperty(name)){
  17.             products[name] = price;
  18.         }
  19.     }
  20.  
  21.     let sortedInitials = Object.keys(catalogue).sort(alphaSort);
  22.  
  23.     for (let initial of sortedInitials){
  24.         console.log(initial);
  25.  
  26.         let products = catalogue[initial];
  27.         let sortedProducts = Object.keys(products).sort(alphaSort);
  28.  
  29.         for(let p of sortedProducts){
  30.             console.log(`  ${p}: ${products[p]}`);
  31.         }
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement