Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter javascript object array by string array

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?

like image 915
Dexter Avatar asked Nov 16 '10 11:11

Dexter


2 Answers

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

like image 80
Nick Craver Avatar answered Sep 24 '22 14:09

Nick Craver


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()

like image 43
Anpher Avatar answered Sep 25 '22 14:09

Anpher