Author Archive

Hello world!

Welcome to WordPress. This is your first post. Edit or delete it, then start writing!

Fillter arrays, objects by multiple values by using underscore JS

We can filter arrays, objects by multiple values by using underscore
Useful to filter array values, large objects, using only matching values of a particular field

in this example, the code filters only managers from the employees object
list of names are used to filters.

      
      var employees = [
         {
           id: 1,
           name: 'Kumar',
           designation:'Manager'
         },
         {
           id: 2,
           name: 'Mani',
           designation:'Engineer'
         },
         {
           id: 3,
           name: 'Akash',
           designation:'Manager'
         },
         {
         	id:4,
          name: 'Sruthi',
           designation:'Tester'
         }
      ];
      
      var managerNames =[ 'Kumar','Akash' ];
    
    var Managers = _.filter(employees, function(i) {
        return this.keys.indexOf(i.name) > -1;
    }, { "keys": managerNames });

console.log(Managers);

Link to JS Fiddle to see it in action