Andrew
Andrew

Reputation: 149

How to compare array of objects to array?

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))

Upvotes: 2

Views: 111

Answers (3)

Adrian Brand
Adrian Brand

Reputation: 21638

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)

Upvotes: 0

Noleli
Noleli

Reputation: 662

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"

Upvotes: 0

Nikhil
Nikhil

Reputation: 6643

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);

Upvotes: 2

Related Questions