The Code

                
                    var events = [
  {
    event: "ComicCon",
    city: "New York",
    state: "New York",
    attendance: 240000,
    date: "06/01/2017",
  },
  {
    event: "ComicCon",
    city: "New York",
    state: "New York",
    attendance: 250000,
    date: "06/01/2018",
  }
  etc...
];


// buil dropdown for specific cities
function buildDropDown(){
    let dropdownMenu = document.getElementById('eventDropDown');
    dropdownMenu.innerHTML = '';

    let currentEvents = getEventData(); // TODO - get these from storage 

    // let cityNames = currentEvent.map(
    //     function (event) {
    //         return event.city
    //     }
    // );

        let cityNames = currentEvents.map(event => event.city)
        let citiesSet = new Set(cityNames);
        let distinctCities = [...citiesSet];

        const dropdownTemplate = document.getElementById('drowdownItemTemplate');

        // make our changes
        let dropdownItemNode = document.importNode(dropdownTemplate.content, true);

        // copy the template
        let dropdownItemLink = dropdownItemNode.querySelector('a');
        dropdownItemLink.innerText = 'All Cities'
        dropdownItemLink.setAttribute('data-string', 'All')

        // add our copy to the page
        dropdownMenu.appendChild(dropdownItemNode);

        for(let i = 0; i < distinctCities.length; i += 1){
            // get the city name
            let cityName = distinctCities[i]

            // generate a dropdown element 
            let itemNode = document.importNode(dropdownTemplate.content, true);
            let anchorTag = itemNode.querySelector('a');
            anchorTag.innerText = cityName;
            anchorTag.setAttribute('data-string', cityName);

            // append it to the dropdown menu 
            dropdownMenu.appendChild(itemNode)
        }
        displayEventData(currentEvents)
        displayStats(currentEvents);
        document.getElementById('location').innerText = 'All Events'
}

function displayEventData(currentEvents){
// get the table 
    const eventTable = document.getElementById('eventTable');
    const template = document.getElementById('tableRowTemplate');

    eventTable.innerHTML = ''

    for(let i = 0; i < currentEvents.length; i++){
        let event = currentEvents[i];
        let tableRow = document.importNode(template.content, true)
        
        tableRow.querySelector('[data-id="event"]').textContent = event.event;
        tableRow.querySelector('[data-id="city"]').textContent = event.city;
        tableRow.querySelector('[data-id="state"]').textContent = event.state;
        tableRow.querySelector('[data-id="attendance"]').textContent = event.attendance.toLocaleString();
        tableRow.querySelector('[data-id="date"]').textContent = new Date(event.date).toLocaleDateString();

        eventTable.appendChild(tableRow); 
    }
}

function calculateStats(currentEvents) {
  let total = 0;
  let average = 0;
  let most = 0;
  let least = currentEvents[0].attendance;

  for (let i = 0; i < currentEvents.length; i++) {
    let currentAttendace = currentEvents[i].attendance;

    total += currentAttendace;

    if (currentAttendace > most) {
      most = currentAttendace;
    }

    if (currentAttendace < least) {
      least = currentAttendace;
    }
  }

  average = total / currentEvents.length;

  let stats = {
    total: total,
    average: average,
    most: most,
    least: least,
  };

  return stats;
}

function displayStats(currentEvents) {
  let statistics = calculateStats(currentEvents);

  document.getElementById("total").textContent = statistics.total.toLocaleString();

  document.getElementById("average").textContent = Math.round(statistics.average).toLocaleString();
  
  document.getElementById("most").textContent = statistics.most.toLocaleString();
  document.getElementById("least").textContent = statistics.least.toLocaleString();
}

function getEventData() {
  let data = localStorage.getItem('daEventStatsData');

  if (data == null){
    localStorage.setItem('daEventStatsData', JSON.stringify(events));
  }

  let currentEvents = data == null ? events : JSON.parse(data);

  // if statement same as the one above, 
  // if (data == null) {
  //   currentEvents = events;
  // } else {
  //   currentEvents = JSON.parse(data);
  // }

  return currentEvents;
}

function viewFilteredEvents(dropdownItem){
  let cityName = dropdownItem.getAttribute('data-string');

  // get all my events
  let allEvents = getEventData();

  if (cityName == 'All'){
    displayStats(allEvents);
    displayEventData(allEvents);
    document.getElementById("location").innerText = "All Events";
   
    return;
  }
    // filter those events to just the selected city
    let filteredEvents = allEvents.filter(event => event.city.toLowerCase() == cityName.toLowerCase());
    
    let filteredEvents2 = allEvents.filter(
      function(event){
        return event.city.toLowerCase() == cityName.toLowerCase();
      })
      
      // display the stats for those events
      displayStats(filteredEvents);
      
      // change the stats header
      document.getElementById('location').innerText = cityName;
      
      // display only those events in the table
      displayEventData(filteredEvents);
}

function saveNewEvent(){
  // get the form input values
  let name = document.getElementById('newEventName').value;
  let city = document.getElementById("newEventCity").value;
  let attendance = parseInt(document.getElementById("newEventAttendance").value, 10);

  let dateValue = document.getElementById('newEventDate').value;
  dateValue = new Date(dateValue);

  let date = dateValue.toLocaleDateString();

  let stateSelect = document.getElementById('newEventState');
  let stateIndex = stateSelect.selectedIndex;

  let state = stateSelect.options[stateIndex].text;
  // create a new event object 
  let newEvent = {
    event: name,
    city: city,
    state: state,
    attendance: attendance,
    date: date,
  };
  // add it to the array of current events 
  let events = getEventData();
  events.push(newEvent)

  // then, save the array with the new event
  localStorage.setItem('daEventStatsData', JSON.stringify(events));

  buildDropDown();
}
                
            
  • buildDropDown
  • displayEventData
  • calculateStats
  • displayStats
  • getEventData
  • viewFilteredEvents
  • saveNewEvent

buildDropDown retrieves the objects from the events variable from the top, it then gets the cities from each event using map and an arrow function and converts them into a set. That set is then converted into an array with a spread and keeps unique cities to use in the dropdown. It then uses getElementById to select our HTML template, importNode copies that selected template, and using querySelector it tells it what HTML tag to target. Using appendChild we push it to the bottom of the list of events. A for loop then iterates through the distinct cities, adding them to a list and creating the dropdown with unique cities.

displayEventData gets the table where the rows will go into and the templates for the rows. It then uses a for loop that goes through every event and fills out the table row using querySelector and dot notation to retrieve the event's name, city, state, attendance, and date.Then, it uses appendChild to add the table row to the table and restarts the loop until all the events are displayed.

calculateStats This function calculates statistics based on the currentEvents array. It iterates through the events, calculating the total attendance, finding the highest and lowest attendance, and finally computing the average attendance. The function returns an object containing the calculated statistics

displayStats This function displays the calculated statistics on the webpage. It retrieves the statistics object from the calculateStats function and updates the corresponding HTML elements with the calculated values.

getEventDataThis function retrieves event data from local storage. If the data is not present in local storage, it initializes it with the events array. It returns the event data either from local storage or the events array.

viewFilteredEvents This function is triggered when a dropdown item is selected. It filters the events based on the selected city and displays the filtered events and corresponding statistics. If "All" is selected, it displays all events.

saveNewEventThis function saves a new event to the events array and updates the data in local storage. It retrieves the input values from the form fields, creates a new event object, adds it to the events array, and saves the updated array in local storage. It then triggers the buildDropDown function to update the dropdown menu.