ambar
ambar

Reputation: 2253

How to filter an Object in Javascript or Underscore with list of array elements as the key

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

Answers (3)

Rūdolfs Vikmanis
Rūdolfs Vikmanis

Reputation: 722

var filteredPopulation = _.object(
  _(population)
   .pairs()
   .filter(function(v) { return cities.indexOf(v[0]) !== -1 })
)

Upvotes: 2

dandavis
dandavis

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

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

var filterObj={};

cities.forEach(function(x){
  filterObj[x]=population [x];
});
console.log(filterObj);

JSFIDDLE

Upvotes: 2

Related Questions