Untitled

Anonymous
plain_text
05/19/2023 9:32 AM
892 B
14
Indexable
// Create an array of objects with state and city
const cities = [
  { state: 'California', city: 'Los Angeles' },
  { state: 'California', city: 'San Francisco' },
  { state: 'New York', city: 'New York City' },
  { state: 'New York', city: 'Albany' },
  { state: 'Texas', city: 'Houston' },
  { state: 'Texas', city: 'Austin' },
];

// Generate an array to collect cities according to the same state
const citiesByState = {};
cities.forEach((item) => {
  const { state, city } = item;
  if (!citiesByState[state]) {
    citiesByState[state] = [city];
  } else {
    citiesByState[state].push(city);
  }
});

// Output the resulting array
console.log(citiesByState);
Editor is loading...