Home > Software engineering >  Vue trying to filter an array but I get no results
Vue trying to filter an array but I get no results

Time:01-05

I have a Vue 3 application

I have an object of posts. Each post has a different category. At the top of the page I have check boxes that I can check to filter the array and only show the categories I added to another array called visibleList. If I click the check box for cars then 'cars' is added to visibleList.

I need to show only posts with the category of cars if I check the cars checkbox. Now if I check the box I see no posts

I created an extra object that I can use to filter the objects. That object is populated when I load the app.

When I check a box the posts disappear. In the console I can see the number of posts with the correct category showing true and the others showing false.

Here is my function for sorting the posts:

function filterPosts() {
    filtered.value = posts.value;
    if (visibleList.value.length != 0) {
        filtered.value = filtered.value.filter((e) => {
            visibleList.value.includes(e.category);
console.log(visibleList.value.includes(e.category));
        });
    } else {
        filtered.value = posts.value;
    }
}

What am I doing wrong that I cannot see the posts from the selected category?

CodePudding user response:

Looks like you are not returning a value from the filter function. The filter function expects a boolean value to determine whether an element should be included in the filtered array or not.

filtered.value = filtered.value.filter((e) => {
    return visibleList.value.includes(e.category);
});

CodePudding user response:

Just an Alternative!!

Since you are using the arrow function, you can use this approach to filter down the value.

filtered.value = filtered.value.filter((e) => visibleList.value.includes(e.category));
  • Related