I can't seem to think about how I can overcome this issue where there might be any amount of filters as objects which will help me to filter out the data array.
data = [
{
id: 1,
first_name: 'Colver',
}, {
id: 2,
first_name: 'Brodie',
}, {
id: 3,
first_name: 'Philippa',
}, {
id: 4,
first_name: 'Taite',
}, {
id: 5,
first_name: 'Pierson'
}
];
filters = [
{
field: 'id',
operator: 'between',
value: '2-5'
},
{
field: 'first_name',
operator: 'eq',
value: 'Philippa'
}
];
ngOnInit(): void {
const filteredItems = [];
this.data.forEach(item => {
this.filters.forEach((filter, filterIndex) => {
const itemValue = item[filter.field];
switch (filter.operator) {
case 'eq':
if (itemValue === filter.value) {
filteredItems.push(item);
}
break;
case 'between':
const [firstValue, secondValue] = filter.value.split('-');
if (itemValue > firstValue && itemValue < secondValue) {
filteredItems.push(item);
}
break;
}
});
});
console.log(filteredItems);
}
I basically want the filteredItems to output like below since the id is between 2 and 5 and the first_name is Philippa. But since I'm iterating the filters 2 times both the times items gets pushed to filteredItems.
[{
id: 3,
first_name: 'Philippa',
}]
'eq'and'between'the only two possible values?