Javascript: How to combine two arrays with duplicate keys into an object

I have two arrays

array1 = [Alabama, Alabama, Georgia, Georgia, Georgia, California ]
array2 = [Mobile, Montgomery, Atlanta, Savannah, Montgomery, San Francisco ]

Both have equal number of elements and essentially for every city in Array 2, there is a corresponding state in the other array but as you can see city names in different states can be the same

I need to convert it into an Object like this in Javascript – This way I can populate a conditional drop down easily when a state is chosen unless someone has an idea to do the same with 2 distinct arrays

var citiesByState = {
   Alabama: ["Mobile","Montgomery"],
   Georgia: ["Savannah","Montgomery"],
   California: ["San Francisco"]
}

Any help would be greatly appreciated

I have tried a few different ways but they create objects of objects as opposed to what I want above.

>Solution :

The Solution :

Don’t forget to give a feedback.

This is the capture when i was trying it

const array1 = ['Alabama', 'Alabama', 'Georgia', 'Georgia', 'Georgia', 'California' ];

const array2 = ['Mobile', 'Montgomery', 'Atlanta', 'Savannah', 'Montgomery', 'San Francisco'];

const objProps = Array.from(new Set(array1));
const citiesByState = {};

objProps.forEach(state => {
  citiesByState[state] = [];
})

array1.forEach((state, idx) => {
  citiesByState[state].push(array2[idx]);
})

console.log(citiesByState);

Leave a Reply