Filter an array of javascript objects with an array of strings

I have an array of objects, for example:

var companies = [ { "name" : "Company 1", "logo" : "/logo.gif" }, { "name" : "Company 2", "logo" : "/logo2.gif" }, { "name" : "Company 3", "logo" : "/logo3.gif" } ]; 

I want to filter this array to only get values ​​that have a name that exists in another array:

 var myCompanies = [ "Company 1", "Company 3" ]; 

In this example, the returned data will be as follows:

 var companies = [ { "name" : "Company 1", "logo" : "/logo.gif" }, { "name" : "Company 3", "logo" : "/logo3.gif" } ]; 

What is the best way to do this?

+4
source share
3 answers

You can use $.grep() to get a new, filtered array, e.g.

 var result = $.grep(companies, function(e) { return $.inArray(e.name, myCompanies) != -1; }); 

Here you can test it . Note that this works much better than $.each() , you can test it here: http://jsperf.com/each-vs-grep

+7
source

Outline only.

 var newArray = []; $.each(companies, function(){ if($.inArray(this.name, myCompanies) !== -1) newArray.push(this); }); 

jQuery is used here: jQuery.each () and jQuery.inArray ()

+1
source

This should be done:

 companies = $.map(companies,function(element){ return ($.inArray(element.name,myCompanies)>-1?element:null) } 
0
source

All Articles