firedrawndagger
firedrawndagger

Reputation: 3733

Using $.grep to match array data to another array

Trying to see if data in one array matches the data in another. I have an array of objects, like so -

var ProductsList =
[
{"Name": "Product A"; "Rating": "3"},
{"Name": "Product B"; "Rating": "2"},
{"Name": "Product C"; "Rating": "1"},
];

I then want to compare this product list with user selected values, which come in an array that I get based on the values they selected via checkboxes. So if they selected 1, 2, 3 - all products should be shown, if they selected 1 - then only product A is shown.

I tried to use $.grep to do the filtering but I'm running into an issue filtering via array values. Let's hard code the user filer to all values as an example.

userFilterArray.Rating = [1, 2, 3];

function filter(ProductsList, userFilterArray)
filteredList = $.grep(ProductList, function(n) {
  return (n.Rating == userFilterArray.Rating);
});

Obviously this doesn't work as I'm comparing n.Rating which is a string to an array but I'm not sure how to compare the string to string in this case.

Would grep be the easiest way to do this? Should I use a combo of .each .each? Maybe neither?

Upvotes: 2

Views: 1829

Answers (1)

user1106925
user1106925

Reputation:

After a bunch of syntax and other fixes, I think this is what you're after:

var ProductsList = [
   {"Name": "Product A", "Rating": 3},
   {"Name": "Product B", "Rating": 2},
   {"Name": "Product C", "Rating": 1}
];

var userFilterArray = [1, 3];

function filter(list, filterArr) {
    return $.grep(list, function(obj) {
        return $.inArray(obj.Rating, filterArr) !== -1;
    });
}

var filteredList = filter(ProductsList, userFilterArray)

console.log( filteredList );

DEMO: http://jsfiddle.net/vK6N9/

Upvotes: 3

Related Questions