Advertisement
dimipan80

Exams - Concerts

Nov 16th, 2014
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* You are given a timetable for the upcoming rock concerts. It consists of bands, towns, dates and venues,
  2.  separated by '|'. Your task is to write a JavaScript function that prints at the console a JSON string that holds
  3.  the towns, venues for each town and list of bands for each venue (see the example below). */
  4.  
  5. "use strict";
  6.  
  7. function printToJSONstring(arr) {
  8.     var i;
  9.     var concertMap = {};
  10.     for (i = 0; i < arr.length; i += 1) {
  11.         var lineArray = arr[i].split('|').filter(Boolean);
  12.         var town = lineArray[1].trim();
  13.         var stadium = lineArray[3].trim();
  14.         var band = lineArray[0].trim();
  15.  
  16.         if (!(town in concertMap)) {
  17.             concertMap[town] = {};
  18.         }
  19.  
  20.         if (!(stadium in concertMap[town])) {
  21.             concertMap[town][stadium] = [];
  22.         }
  23.  
  24.         if (concertMap[town][stadium].indexOf(band) == -1) {
  25.             concertMap[town][stadium].push(band);
  26.         }
  27.     }
  28.  
  29.     var townKeys = Object.keys(concertMap).sort();
  30.     var outputMap = {};
  31.     for (i = 0; i < townKeys.length; i += 1) {
  32.         outputMap[townKeys[i]] = {};
  33.         if (concertMap.hasOwnProperty(townKeys[i])) {
  34.             var stadiumKeys = Object.keys(concertMap[townKeys[i]]).sort();
  35.             for (var j = 0; j < stadiumKeys.length; j += 1) {                
  36.                 if (concertMap[townKeys[i]].hasOwnProperty(stadiumKeys[j])) {
  37.                     outputMap[townKeys[i]][stadiumKeys[j]] = concertMap[townKeys[i]][stadiumKeys[j]].sort();
  38.                 }
  39.             }
  40.         }
  41.     }
  42.  
  43.     console.log(JSON.stringify(outputMap));
  44. }
  45.  
  46. printToJSONstring([
  47.     'ZZ Top | London | 2-Aug-2014 | Wembley Stadium',
  48.     'Iron Maiden | London | 28-Jul-2014 | Wembley Stadium',
  49.     'Metallica | Sofia | 11-Aug-2014 | Lokomotiv Stadium',
  50.     'Helloween | Sofia | 1-Nov-2014 | Vassil Levski Stadium',
  51.     'Iron Maiden | Sofia | 20-June-2015 | Vassil Levski Stadium',
  52.     'Helloween | Sofia | 30-July-2015 | Vassil Levski Stadium',
  53.     'Iron Maiden | Sofia | 26-Sep-2014 | Lokomotiv Stadium',
  54.     'Helloween | London | 28-Jul-2014 | Wembley Stadium',
  55.     'Twisted Sister | London | 30-Sep-2014 | Wembley Stadium',
  56.     'Metallica | London | 03-Oct-2014 | Olympic Stadium',
  57.     'Iron Maiden | Sofia | 11-Apr-2016 | Lokomotiv Stadium',
  58.     'Iron Maiden | Buenos Aires | 03-Mar-2014 | River Plate Stadium'
  59. ]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement