Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading