Categories
Vue Answers

How to filter on array with Vue.js?

Spread the love

Sometimes, we want to filter on array with Vue.js.

In this article, we’ll look at how to filter on array with Vue.js.

How to filter on array with Vue.js?

To filter on array with Vue.js, we can return the filtered array in a computed property.

For instance, we write

<template>
  <div>
    <div>
      <input type="text" v-model="search" />
      <label>Search Users:</label>
    </div>
    <ul>
      <li v-for="user in filteredAndSorted" :key="user.id">{{ user.name }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  //...
  data() {
    return {
      search: "",
      userList: [
        {
          id: 1,
          name: "Prem",
        },
        {
          id: 1,
          name: "Chandu",
        },
        {
          id: 1,
          name: "Shravya",
        },
      ],
    };
  },
  computed: {
    filteredAndSorted() {
      const compare = (a, b) => {
        if (a.name < b.name) return -1;
        if (a.name > b.name) return 1;
        return 0;
      };

      return this.userList
        .filter((user) => {
          return user.name.toLowerCase().includes(this.search.toLowerCase());
        })
        .sort(compare);
    },
  },
  //...
};
</script>

to create the filteredAndSorted to return the userList array filtered and sorted.

We filter the values by the this.search value that we get from typing in the input.

v-model updates the this.search value with the latest input value.

Then we use v-for to render all the items in the filteredAndSorted array.

Conclusion

To filter on array with Vue.js, we can return the filtered array in a computed property.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to filter on array with Vue.js?”

Leave a Reply

Your email address will not be published. Required fields are marked *