2

I have an array of objects and array of strings

cities = [ { id: '1', name: 'Paris'}, { id: '2', name: 'Rome'}, { id: '3', name: 'London'}, { id: '4', name: 'Barcelona'}]

userChoice = ['2','4']

I need to iterate over cities with userChoice and find name of cities by id. I guess it's going to be a nested loop, but I am strugling with it.

cities.filter(city=> userChoice.forEach(choice => choice == city.id))
0

3 Answers 3

2

You can use filter() and includes() to filter cities array by checking if a city's id is present in userChoice array.

To get just the names, you can use map() to transform the result.

let cities = [ { id: '1', name: 'Paris'}, { id: '2', name: 'Rome'}, { id: '3', name: 'London'}, { id: '4', name: 'Barcelona'}];
let userChoice = ['2','4'];

let filteredCities = cities.filter(city => userChoice.includes(city.id));

let names = filteredCities.map(city => city.name);

console.log(names);

Sign up to request clarification or add additional context in comments.

1 Comment

includes() doesn't work on IE. If you want to make it work on all the devices and browsers, it would be better to use indexOf(). i.e userChoice.indexOf(city.id) > -1
0

You could use a Map object to look up ID based on city.

let cityMap = new Map(cities.map(c => [c.name, c.id]));
console.log(cityMap.get("Rome")); // --> "2"

Comments

0

Just use a simple map, you map the array element to the city from the other array. You might want to put a null check in if you can have values that might not be in the array but for simplicity I left it out.

const cities = [ { id: '1', name: 'Paris'}, { id: '2', name: 'Rome'}, { id: '3', name: 'London'}, { id: '4', name: 'Barcelona'}];

const userChoice = ['2','4'];

const userCities  = userChoice.map(val => cities.find(c => c.id === val).name);

console.log(userCities)

2 Comments

cities.find(c => c.id === val).name will get a reference error when there is no city with an id in userChoice. It should handle that exception.
I have mentioned that "You might want to put a null check in if you can have values that might not be in the array but for simplicity I left it out."

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.