My current task involves working with a list of objects, each object having 4 properties. To aid in filtering these objects, there is a checkbox list containing unique values from two of the properties.
The generated Filter array could appear as follows:
[
{
prop: 'username',
val: ['max', 'sam']
},
{
prop: 'color',
val: ['blue', 'green']
}
]
Here's an example of the list of objects:
[
{
username: 'sam',
color: 'blue'
},
{
username: 'jimmy',
color: 'blue'
},
{
username: 'sam',
color: 'black'
},
{
username: 'max',
color: 'green'
},
{
username: 'max',
color: 'blue'
}
]
The Desired Result is:
[
{
username: 'sam',
color: 'blue'
},
{
username: 'max',
color: 'green'
},
{
username: 'max',
color: 'blue'
}
]
I'm currently using a loop to filter through the transactions, but it feels like an endless cycle. I suspect that recursion may provide a solution. Here's my existing code:
var temporary = scope.transactions;
function getFilteredTransactions() {
var filter = deviceFilterService.get();
if (filter.length > 0) {
var temp2 = [];
angular.forEach(filter, function (fil) {
angular.forEach(fil.val, function (filterValue) {
angular.forEach(temporary, function (transaction) {
if (transaction[fil.prop] === filterValue) {
if (temp2.indexOf(transaction) === -1) {
temp2.push(transaction);
}
}
});
temporary = temp2;
});
});
$log.debug(temporary);
scope.transactions = temporary;
} else {
initialize();
}
}
While this approach works initially, it runs into issues during the second iteration for the color
property. It seems to want to add the same transaction to the temp2
array. There must be a more efficient way to handle this situation, possibly involving recursion.