I'm building a sorting system using checkbox to filter some businesses. I did found an awesome answer here.
The problem is, it's using only a single element. In my case i want to filter by business category and some of them can have up to 3 categories. So I'm kind of stuck in there because i don't know how to proced to get the unique arrays and then to apply the filter.
In my case what i need is:
- Get the business list from database;
- Create an array with all the unique category taken from each business;
- Create an checkbox list with these unique categories;
- When select one checkbox, show all the business within that selected category.
Here is a simple fiddle of the working version: http://jsfiddle.net/zo47y6es/1/
It only has 1 option per category;
Here is a fiddle with the list i want to make work: http://jsfiddle.net/zo47y6es/2/
Which is an list of category for each business.
This is the code i made (simple version) based on the answer from that topic:
app.js
//Loop and create unique items for checkbox
var uniqueItems = function (data, key) {
var result = [];
for (var i = 0; i < data.length; i++) {
var value = data[i][key];
if (result.indexOf(value) == -1) {
result.push(value);
}
}
return result;
};
//Default array. Comes from the page where we select the checkbox
$scope.useCategory = {};
$scope.$watch(function () {
return {
business: $scope.business,
useCategory: $scope.useCategory
}
}, function (value) {
var selected;
//Update filter couting
$scope.count = function (prop, value) {
return function (el) {
return el[prop] == value;
};
};
//Unique items to create filter in the page
$scope.categoryGroup = uniqueItems2($scope.business);
//Execute the filter process in the category
var filterAfterCheck = [];
selected = false;
for (var j in $scope.business) {
var p = $scope.business[j];
for (var i in $scope.useCategory) {
if ($scope.useCategory[i]) {
selected = true;
if (i == p.categoria) {
filterAfterCheck.push(p);
break;
}
}
}
}
if (!selected) {
filterAfterCheck = $scope.business;
}
$scope.filteredBusiness = filterAfterCheck;
}, true);
I started trying to play with it but i already got some errors in the uniqueItems
process and couldn't go further.
var uniqueItems2 = function (data) {
var result = [];
for (var i = 0; i < data.length; i++) {
var value = data[i].category;
if (result.indexOf(value) == -1) {
result.push(value);
}
}
return result;
};
And my array looks like this:
$scope.business = [
{
"id":1,
"name":"aaa 001",
"category":[
"Food",
"Market"
],
"rating":"99%",
"open":"O"
},
{
"id":2,
"name":"aaa 002",
"category":[
"Clothes",
"Shoes",
"Dress"
],
"rating":"99%",
"open":"O"
},
{
"id":1,
"name":"aaa 001",
"category":[
"Market",
"Other"
],
"rating":"99%",
"open":"O"
}
]
Does anyone knows how should i procced to achieve this result? I need to filter the business based on the category eventought they may have multiple categories (in my case, up to 5 per business).