Untitled

 avatar
unknown
plain_text
2 years ago
668 B
2
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);