Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eddieace's avatar

Computed property with multiple checkbox filters

I am trying to make a solution for filtering results using checkboxes as simple as possible and as readable as possible.

I have a computed property called filteredPositions that looks like this. But it won't work with multiple filters on one array. Does anyone have a good solution for this problem?

Here is the computed property.

filteredPositions() {
    if (this.checkedFilters.includes("SE")) {
        return this.positions.filter(position => position.country_id == 1);
    }
    if (this.checkedFilters.includes("US")) {
        return this.positions.filter(position => position.country_id == 2);
    }
}

Testdata

data() {
    return {
        positions: [],
        filters: [
            {
                name: 'SE',
            },
            {
                name: 'US',
            }
        ],
        checkedFilters: ['SE', 'US'],
    }
},

Here is a jsFiddle https://jsfiddle.net/0dzvcf4d/9657/

0 likes
1 reply
rawilk's avatar

It's not working because you are returning in each if check. I'd recommend using the ids instead of the names in the checkedFilters to make it easier to filter. I think something like this should work:

data () {
    return {
        positions: [],
        filters: [
            { name: 'SE', id: 1 },
            { name: 'US', id: 2 }
        ],
        checkedFilters: [1, 2]
    };
},

computed: {
    filteredPositions () {
        return this.positions.filter(position => this.checkedFilters.includes(position.country_id));
    }
}
1 like

Please or to participate in this conversation.