Reputation: 11
Is it my syntax, or is what I'm trying to do just completely the wrong way of going about this?
I have two arrays that are populated by whatever attributes the user selects. Then I'm trying to use $.grep() on a json file to select pillows that match their search. So in the example below, I'm trying to find all pillows with a "down" fill and a "low" price.
var activevars = ['fill','price'];
var activeattributes = ['down','low'];
pillowSelection = $.grep(data.pillow, function (a) {
return $.inArray(a[activevars], activeattributes) > -1;
});
I'm a tenacious Googler, but this has me stumped. Thanks so much in advance for any clues.
Upvotes: 1
Views: 3233
Reputation: 61
This was the way i solved my problem:
var array1 = [1,2,3,4,5],
array2 = [5,4,3,2,1,6];
function compareArrays(arr1, arr2) {
return $(arr1).not(arr2).length == 0
};
Then run this in a for each loop:
var hasValues = compareArrays(array1, array2) ? 'true' : 'false');
if(hasValues == true){
// show content
}else{
// Hide content
}
Upvotes: 0
Reputation: 60463
If I understand correctly, activevars
and activeattributes
are parallel arrays, that is activevars[0]
goes with activeattributes[0]
and activevars[1]
goes with activeattributes[1]
, etc.
So you could do something like this:
pillowSelection = $.grep(data.pillow, function(a) {
for (var i = 0; i < activevars.length; i++) {
if (a[activevars[i]] !== activeattributes[i]) {
return false;
}
}
return true;
});
If you want a more functional style, you should use an object representing the active attributes/vars (or just convert from parallel arrays); eg.
var filter = { fill: 'down', price: 'low' };
and then check whether it is a sub dictionary of each pillow:
pillowSelection = $.grep(data.pillow, function(a) {
return sub_dictionary(filter, a);
});
Upvotes: 2
Reputation: 17815
There seems to be something missing from your question, but I'll try to answer it like so:
If you have an array of pillow objects:
var pillows = [
{ fill: 'down', price: 'low' },
{ fill: 'cheese', price: 'middle' },
{ fill: 'water', price: 'high' },
{ fill: 'air', price: 'omg-too-much' }
];
To get a new array of pillows matching your criteria, form your query this way and it will be much easier:
var query = { fill: 'down', price: 'low' };
var matches = pillows.filter(function (pillow) {
return pillow.fill === query.fill && pillow.price === query.price;
});
Upvotes: 1
Reputation: 50167
This should work for you:
var activevars = ['fill', 'price'];
var activeattributes = ['down', 'low'];
var pillowSelection = $.grep(data.pillow, function(a) {
var ret = false;
for (var i = 0, il = activevars.length; i < il; i++) {
if ($.inArray(a[activevars[i]], activeattributes) > -1) {
ret = true;
}
}
return ret;
});
Upvotes: 0