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

How to get the same value from 2 different arrays

const selectedAnimals = ['lion','tiger','elephant','deer','bird','turtle']
const zoo = [{id: '1', name:'lion'},{id: '2', name:'panda'},{id: '3', name:'tiger'},{id: '4', name:'rabbit'},{id: '5', name:'bear'},{id: '6', name:'elephant'},{id: '7', name:'deer'},{id: '8', name:'bird'},{id: '9', name:'turtle'}]

Hi! There are two different arrays and I want to compare two arrays and find the id of selected animals from the zoo. How do I get the array of ids? Also, the id has to be a string. Thank you

>Solution :

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

Make a look-up table that gives the ID for each name, then use this to get the IDs of each selected animal.

const selectedAnimals = ['lion','tiger','elephant','deer','bird','turtle'];
const zoo = [{id: '1', name:'lion'},{id: '2', name:'panda'},{id: '3', name:'tiger'},{id: '4', name:'rabbit'},{id: '5', name:'bear'},{id: '6', name:'elephant'},{id: '7', name:'deer'},{id: '8', name:'bird'},{id: '9', name:'turtle'}];
const idByName = Object.fromEntries(zoo.map(item => [item.name, item.id]));
console.log(selectedAnimals.map(name => idByName[name]));
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