I have the following javascript array, in which I need to return the matching city names.
[['75', 'Paris'], ['456', 'Marseille'], ['634', 'Toulouse'], ['668', 'Lyon'], ['035', 'Saint-Étienne']]
When input is 634, the javascript function will return Toulouse.
When input is 634, 75, then the return will be a list of comma separated cities. ‘Toulouse, Paris’
When input is 634, 75, 668 then the return will be a list of comma separated cities. ‘Toulouse, Paris, Lyon’
Any ideas?
3
Answers
To achieve this, you can write a JavaScript function that takes an array of city pairs (each pair being an array with an ID and a city name) and a list of IDs as input. The function then filters the city pairs based on whether their IDs match any of the input IDs, maps the matching pairs to their city names, and joins these names into a comma-separated string. Below is a function that implements this logic:
This function uses the
filter
method to keep only the city pairs where the ID matches one of the input IDs. It then usesmap
to transform the filtered array of pairs into an array of city names. Finally, it usesjoin
to concatenate all city names into a single string separated by commas.The function
findCities
is defined to take multipleinputIds
using rest parameters (...inputIds
), allowing you to pass one or more IDs as separate arguments rather than needing an array. This makes the function flexible and easy to use with different numbers of input IDs.You can use the
Array.find()
method to search for a matching city for each input number. If a match is found, it adds the corresponding city name to thematchingCities
array. Then you can join to create a comma-separated string of the matching cities.You can use Object.fromEntries to make a lookup object, like this: