Untitled

 avatar
unknown
plain_text
2 years ago
1.6 kB
5
Indexable
// Array of objects representing states and cities
const locations = [
  { state: 'California', city: 'Los Angeles' },
  { state: 'California', city: 'San Francisco' },
  { state: 'New York', city: 'New York City' },
  { state: 'New York', city: 'Buffalo' },
  { state: 'Texas', city: 'Houston' },
  { state: 'Texas', city: 'Austin' }
];

// Function to collect cities by state and print them with related states
function collectCitiesByState(locations, callback) {
  // Object to store the collected cities
  const collectedCities = {};

  // Iterate over each location object
  for (const location of locations) {
    const { state, city } = location;

    // Check if the state already exists in the collectedCities object
    if (!collectedCities[state]) {
      collectedCities[state] = [];
    }

    // Push the city to the corresponding state array
    collectedCities[state].push(city);
  }

  // Call the callback function and pass the collectedCities object
  callback(collectedCities);
}

// Callback function to print the collected cities with their related states
function printCitiesByState(collectedCities) {
  for (const state in collectedCities) {
    if (collectedCities.hasOwnProperty(state)) {
      const cities = collectedCities[state];
      console.log(`State: ${state}`);
      console.log(`Cities: ${cities.join(', ')}`);
      console.log('------------------------');
    }
  }
}

// Call the collectCitiesByState function with the locations array and the printCitiesByState callback function
collectCitiesByState(locations, printCitiesByState);
Editor is loading...