I have an array of objects, like this:
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 get only values which have a name which exists in another array:
var myCompanies = [ "Company 1", "Company 3" ];
In this example, the data to be returned would be:
var companies = [
{ "name" : "Company 1",
"logo" : "/logo.gif" },
{ "name" : "Company 3",
"logo" : "/logo3.gif" } ];
What's the best way to do this?
You can use $.grep()
to get a new, filtered array, like this
var result = $.grep(companies, function(e) {
return $.inArray(e.name, myCompanies) != -1;
});
You can test it here. Note that this performs much better than a $.each()
loop, you can test it here: http://jsperf.com/each-vs-grep
By loop only..
var newArray = [];
$.each(companies, function(){
if($.inArray(this.name, myCompanies) !== -1) newArray.push(this);
});
jQuery utilies are used here: jQuery.each() and jQuery.inArray()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With