I have a <SELECT multiple="multiple"> box with options.
I store the selected options in a JS variable – selectedFeatures.
I want to pass selectedFeatures array variable of options to jQuery.inArray() – but the function is designed to take and check for one value only.
I can show/hide( or filter ) the markers on my map if I actually specify an index of an element like so: selectedFeatures[0] inside inArray()
..but since I may select multiple options from a select box this method of filtering doesn’t work.
How can I check if an array of items in found inside another array with JS/jQuery?
// store selected options as an array of string elements inside the variable
var selectedFeatures = $("#features").val();
// for every element inside 'markers.houses' array...
$(markers.houses).each(function(index, elem){
// check if any of the values inside the 'selectedFeatures' array are found
// also inside a sub-array 'features' inside every element of 'markers.houses'
// array. if 'true' show that particular marker, otherwise hide the marker
if(jQuery.inArray(selectedFeatures, elem.features) !== -1 || jQuery.inArray(selectedFeatures, elem.features) > -1){
markers.houseMarkers[index].setVisible(true);
}else{
markers.houseMarkers[index].setVisible(false);
}
});
Fig 1.1 – store selected options in an array variable and use it with
jQuery.inArray()
What you are asking for can be solved with PHP’s
array_difffunction. I know you’re not using PHP, but that’s why there isarray_diffon PHPJS, a project dedicated to porting PHP functions into JavaScript.Anyway, to solve this you basically want to call
array_diff(selectedFeatures,elem.features).length == 0. (You may need to swap the arguments around, I’m not sure which array is which in your question)array_diffreturns the elements of the first array that are not present in the others. If all of the elements in the first array are also in the second array (ie. array1 is a subset of array2), then the returned array will be empty, hence its length is zero.