Reputation: 513
I have a multiple selectbox, and i try to get the filtered data based on the multpile propery selected LIKE THIS EXAMPLE
var names = [
{ name : "Joe", age:20, email: "[email protected]"},
{ name : "Mike", age:50, email: "[email protected]"},
{ name : "Joe", age:45, email: "[email protected]"}
];
var filteredNames = $(names).filter(function( idx ) {
return names[idx].name === "Joe" && names[idx].age < 30;
});
But In my case, i want to filter by an array of values
// data selected
var nameselected= $('select[name="usernames"]').val();
var ageselected= $('select[name="ages"]').val();
var filteredNames = $(names).filter(function( idx ) {
return names[idx].name IN ( nameselected ) && names[idx].age IN (ageselected);
});
can i do that !
Upvotes: 2
Views: 49
Reputation: 32145
If you want to filter all the items that have names in selectednames
array and ages in selectedages
array you can do the foloowing:
var filteredNames = names.filter(function(item) {
return nameselected.indexOf(item.name) > -1 && ageselected.indexOf(item.age) > -1;
});
Demo:
var names = [{
name: "Joe",
age: 20,
email: "[email protected]"
},
{
name: "Mike",
age: 50,
email: "[email protected]"
},
{
name: "John",
age: 45,
email: "[email protected]"
}
];
//var nameselected= $('select[name="usernames"]').val();
//var ageselected= $('select[name="ages"]').val();
var nameselected = ["Joe", "John"];
var ageselected = [20, 45];
var filteredNames = names.filter(function(item) {
return nameselected.indexOf(item.name) > -1 && ageselected.indexOf(item.age) > -1;
});
console.log(filteredNames);
Note:
Note that you better use Javascript Array
functions to loops over your array instead of using jQuery methods and complicating things.
Note that this will only return items with ages in selectedages
array, and not ages lower than selectedages
values, in that case
you need to sort the array
of ages to check for the item that is
lower than the lowest value.
Upvotes: 1
Reputation: 14702
I think you can use the indexOf (value of result >-1 if value is inside an array ) to check if your data value is inside your array of selected value
See beloow Snippet :
var names = [
{ name : "Joe", age:20, email: "[email protected]"},
{ name : "Mike", age:50, email: "[email protected]"},
{ name : "Joe", age:45, email: "[email protected]"},
{ name : "Doe", age:40, email: "[email protected]"}
];
var nameselected = ["Joe","Doe"];
var ageselected = [20,40,35];
var filteredNames = $(names).filter(function( idx ) {
return (nameselected.indexOf(names[idx].name)>-1 && ageselected.indexOf(names[idx].age)>-1);
});
$.each(filteredNames,function(index,name){
console.log(name);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1