5

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?

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the jsperf link - I hadn't heard about it before and it's a really nice tool. I added in a test case for $.map() at jsperf.com/each-vs-grep/4 (it's clearly the slowest of the three answers)
1

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

1 Comment

You can do this, but note it's much more expensive (due to the extra scope creation for this), you can compare it to $.grep() here: jsperf.com/each-vs-grep
0

This should to the job:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.