3

I am working with List Rendering in Vue2. The list renders OK, but is ordered based on the order of the data in my array. Therefore, I need to sort each item on screen by title (a-z). I can not seem to figure out how to do this when I also have a search input (filteredBlogs) in use as well. Any help welcome.

   const app = new Vue({
        el: '#app',
        data: {
            search: '',
             blogs: [
              { 
                title: 'Northern Towns' ,
                location: 'Leeds'
              },
              { 
                title: 'Things to do in Leeds' ,
                location: 'Yorkshire'
              },
              { 
                title: 'Visit the beach',
                location: 'Cornwall'
              }
            ]
        },
    computed: {
        filteredBlogs:function(){
            return this.blogs.filter((blog) => {
              return blog.title.toLowerCase().match(this.search.toLowerCase()) ||  blog.location.toLowerCase().match(this.search.toLowerCase());
              .sort((a, b) => {
                  if (a.title < b.title)
                      return -1;
                  if (a.title > b.title)
                      return 1;
                  return 0;
            });
        }
    }
    });

HTML is as follows;

<div id="app">
    <label>
        Search name: <input type="text" v-model='searchString'>
    </label> <br>
    <li v-for='item in filteredBlogs' :key='item.id' class="my-list-item">
        {{item.title}}
    </li>
</div>

1 Answer 1

3

First you filter an original array, second you sort filtered array

computed: {
  filteredBlogs:function(){
    const filteredBlogs = this.blogs.filter((blog) => blog.title.toLowerCase().match(this.search.toLowerCase()) ||  blog.location.toLowerCase().match(this.search.toLowerCase()))
    filteredBlogs.sort((a, b) => {
                  if (a.title < b.title)
                      return -1;
                  if (a.title > b.title)
                      return 1;
                  return 0;
            });
    return filteredBlogs
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.