Reputation: 2253
I have the following object and array, respectively.
cities = ['Berlin', 'Melbourne', 'Dallas']
population = { 'Amsterdam': 100, 'Berlin': 150, 'Cairo': 200, 'Jakarta': 300, 'Melbourne':350, 'Dallas': 400, 'Buenos Aires': 100}
And I would like to filter the population based on the cities mentioned in the array. The output will look as below.
Order does not matter
filtered_population = {'Berlin': 150, 'Melbourne':350, 'Dallas': 400}
What is the best way to do it with writing least amount of code?
Upvotes: 0
Views: 45
Reputation: 722
var filteredPopulation = _.object(
_(population)
.pairs()
.filter(function(v) { return cities.indexOf(v[0]) !== -1 })
)
Upvotes: 2
Reputation: 16726
you can use reduce() to avoid a "side var":
var cities = ['Berlin', 'Melbourne', 'Dallas'],
population = { 'Amsterdam': 100, 'Berlin': 150, 'Cairo': 200, 'Jakarta': 300, 'Melbourne':350, 'Dallas': 400, 'Buenos Aires': 100};
_.reduce(cities, function(a,b){ a[b]=population[b]; return a; },{});
// == {Berlin: 150, Melbourne: 350, Dallas: 400}
Upvotes: 2
Reputation: 25352
Try like this
var filterObj={};
cities.forEach(function(x){
filterObj[x]=population [x];
});
console.log(filterObj);
Upvotes: 2