What's the best way to organize a list while implementing List Rendering in VueJS?

Currently, I am working on List Rendering in Vue2. The list is rendering correctly, but it appears ordered based on the data arrangement in the array. For better organization, I need to sort each item alphabetically by title. However, I am facing difficulty in achieving this while also using a search input (filteredBlogs). Any assistance or guidance on this matter would be greatly appreciated.

   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;
            });
        }
    }
    });

The HTML structure 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>

Answer №1

First, start by filtering the original array and then proceed to sort the 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
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript CheckBox Color Change Not Functioning

Hello, I am currently experimenting with the checkAll function. When I click on the checkAll checkbox, it should select all rows and change their background color accordingly. Below is the JavaScript code I am using: function checkAll(objRef) { v ...

Tips for retaining form inputs without the need for a submit event when the page is reloaded or refreshed

I have a form on a page with multiple text inputs In addition to the form, I have implemented Zend pagination to allow users to select results. However, when using Zend paginate, the user's form inputs are lost because it is not submitted. Since th ...

Warning: Knex was unable to acquire a connection due to a timeout, resulting in an UnhandledPromiseRejectionWarning

I'm having trouble connecting my Telegram bot to the database using knex. I am working with MySQL, and I have already created the database and tables which are visible on the /phpMyAdmin page. The credentials used for accessing the database in my code ...

Is it possible to utilize a JSON file to input events into FullCalendar that can accommodate multiple users?

Here's how I'm integrating event information from my database with FullCalendar using PHP: Retrieve event information from the database. Organize the data into an array and customize formatting, colors, etc. Convert the array to JSON format usi ...

Uploading files using Remix.run: Transforming a File object into a string during the action

I'm currently developing a Remix application that allows users to upload files through a form. I have a handler function for handling the form submission, which takes all the form data, including file attachments, and sends it to my action. The probl ...

Step-by-step guide on programmatically closing the Material-UI DropDownMenu

http://www.material-ui.com/#/components/dropdown-menu Having encountered a styling issue, I was compelled to rearrange the order of components within my material-ui DropdownMenu. Nevertheless, some buttons (renderNavLink) are now failing to close the Dro ...

A cutting-edge combination of Laravel version 6.4.1, webpack, Vue.js, and SCSS for dynamic

I have Laravel 6.4.1 installed with some minor tweaks to the default webpack configuration. I am utilizing Vue components along with scoped styling in my project. Upon running npm run dev, everything functions as expected. My Vue component loads and displ ...

Rendering DataTable content seamlessly from a different webpage using JavaScript without sacrificing control

Is it possible to dynamically call HTML content from Page2.html into Page1.html by utilizing DataTables (https://datatables.net/)? Page1.html <!DOCTYPE html> <html> <head> <title></title> <meta http-equiv="Content-Type" c ...

After a push to the router, scrolling is disabled

While working on a Vuejs project, I encountered an issue when trying to change the page of my PWA using this.$router.push();. It seems to work fine everywhere else except when doing it from a modal within a component. The pushed page loads but scrolling is ...

Using JSTL tags may result in returning null or empty values when making Javascript calls or populating HTML

This strange error is puzzling because it appears on some of the webpages I create, but not on others, even though the elements are exactly the same. For instance, this issue does not occur: <main:uiInputBox onDarkBG="${hasDarkBG}" name="quest ...

Interacting with HTML elements in Java programming

I am facing a challenging situation that requires some brainstorming. I would greatly appreciate any advice or guidance in the right direction. My goal is to incorporate a Google Map into my Java Swing project, with the map being specified as a URL wit ...

Modifying the language of the response (error/success) in stripe.js

I have successfully implemented stripe.js v2 for processing payments in my application catering to a French client. Everything is working smoothly, but I am facing an issue with form validation. I want the error messages to be displayed in French instead o ...

Firefox seems to handle webpages smoothly, whereas IE struggles to display them properly

Check out the code snippet below: self.xmlHttpReq = new XMLHttpRequest(); self.xmlHttpReq.onreadystatechange = function() { if(self.xmlHttpReq.readyState == 4 && self.xmlHttpReq.status == 200) { xmlDoc = self.xmlHttpReq.response ...

Add a variety of input values to a div in designated spots

Objective: The aim is to allow the user to connect form fields with specific locations within a content from another div, and then add the text entered in individual input fields to those corresponding locations. Here is the link to the fiddle HTML: < ...

challenges with template inheritance: when one template takes precedence over another

I have encountered an issue with my two HTML templates, login.html and signup.html. Both of these files inherit from the base.html file, but there seems to be a problem where one file is overriding the title and content of the other. So when I visit /login ...

Is it possible to dispatch actions from getters in Vuex?

Fiddle : here Currently, I am in the process of developing a web application using Vue 2 with Vuex. Within my store, I aim to retrieve state data from a getter. My intention is for the getter to trigger a dispatch and fetch the data if it discovers that t ...

What is the best way to delete a container when its child element includes a specific string?

I run a website that compiles video clips from various sources, including YouTube. Occasionally, some clips appear as private videos. I am looking to use jQuery to apply the display:none; property to the entire div when the class a.colorbox.cboxElement con ...

Insert a CSS Class into an HTML div element with JQuery

I'm faced with a bit of a challenge. Here's the scenario: <div class="portItem"></div> <div class="portItem"></div> <div class="portItem"></div> <div class="p ...

PHP scheduler alternative

I have a PHP script called updater.php that performs a task for 1-2 minutes. It is crucial for the script to complete its job. While I can schedule it with cron, I have come up with an alternative solution. The script should only run at specific times wh ...