I'm currently trying to filter an array by multiple filters stored in another array. A filter-object contains the name of the attribute we want to filter, the operator and the condition. So it could look like this:
let filters = [{
attribute: 'id',
operator: '<',
condition: 5
}, {
attribute: 'name',
operator: '=',
condition: 'Max'
}]
And the Array with the item could look like this:
const items = [{
id: 0,
name: 'Max',
nachname: 'Maier'
}, {
id: 1,
name: 'Peter',
nachname: 'Huber'
}, {
id: 2,
name: 'Max',
nachname: 'Brooks'
}, {
id: 3,
name: 'Sara',
nachname: 'Scott'
}, {
id: 4,
name: 'Peter',
nachname: 'Evans'
}]
Can you please help me out?
My current solutions (see below) always returns all elements. So it doesn't filter anything.
items.filter((item) => {
filters.forEach((filter) => {
switch (filter.operator) {
case '<':
if (!(item[filter.attribute] < filter.condition)) return false
break
case '<=':
if (!(item[filter.attribute] <= filter.condition)) return false
break
case '=':
if (!(item[filter.attribute] === filter.condition)) return false
break
case '>':
if (!(item[filter.attribute] > filter.condition)) return false
break
case '>=':
if (!(item[filter.attribute] >= filter.condition)) return false
break
case '*wildcard*':
if (!item[filter.attribute].includes(filter.condition))
return false
break
}
})
return true
})
Thanks in advance! :)