How to Utilize Multiple .includes in Vue.js Computed Properties?

I attempted to incorporate multiple .includes and .filters in my Vue.js computed function, but I have been unable to achieve success.
HTML:

<input class="searchbar" v-model="filterByName" placeholder="Search By Name" oninput="handleInput(event)">
<button type="button" class="btn btn-lg btn-primary">Advanced [BETA]</button>

<div class="padded">
  <p>
    All 9mm & 9×19mm are 9×19mm Parabellum unless otherwise stated. All Rate of Fire are SEMI-AUTOMATIC unless otherwise
    stated.
  </p>
  <p>** - Still in testing phase (test place)</p>
</div>

...

JS

function handleInput(e) {
  var ss = e.target.selectionStart
  var se = e.target.selectionEnd
  e.target.value = e.target.value.toUpperCase()
  e.target.selectionStart = ss
  e.target.selectionEnd = se
}

new Vue({
  el: "#main",
  data: {
      ...
  },

  computed: {
    sortedlists() {
      return this.lists
        .filter((list) => list.name.includes(this.filterByName))
        .sort((a, b) => a[this.sortBy] - b[this.sortBy])
    },
  },
})

I have been attempting to add another filter using

list => list.name.includes(this.filterByCal)
, along with an additional input with "v-model='filterByCal'" but I have not had success. Can anyone offer any assistance or guidance? Thank you!

Answer №1

The sorting algorithm mistakenly assumes that all values are numbers:

.sort((a, b) => a[this.sortBy] - b[this.sortBy]) ❌ values are not numeric

In reality, the values are strings, and subtracting strings results in NaN, causing the sorting to malfunction.

To address this issue, it is recommended to validate the strings for numerical content before calculating the difference between them. If they are not numbers, use String.prototype.localeCompare for comparison instead:

.sort((a, b) => {
  const aVal = a[this.sortBy]
  const bVal = b[this.sortBy]

  // only perform numerical comparison if both values are numbers
  if (/^\d+$/.test(aVal) && /^\d+$/.test(bVal)) {
    return aVal - bVal
  } else {
    return aVal.localeCompare(bVal)
  }
})

see demo

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

What is the best way to showcase varying colors in HTML content pulled from a database?

I have a MySQL database with 15 or more rows that I want to retrieve and display in alternating colors. For the first row: <tr><td height="30" bgcolor="#F5F5F5">....</td></tr> For the second row: <td height="30" align="center" ...

Generate an additional CSS animation to display before the next page is loaded

When loading a page, I am implementing CSS transitions to display animated lines. To activate these lines, I am utilizing a jQuery script to change the class on the line elements. I am looking to reverse the CSS transitions when transitioning to the next ...

What is the best way to retrieve the value of a nested object within an object that has an integer property in JavaScript?

hello = [ { 0: { symbol: "asdf" , name:"adad"} }] In JavaScript, how can you access the symbol property in the 'hello' array? When you run console.log(hello[0]), it will output { symbol: "asdf" , name:"adad"}. However, if you try to access it u ...

Comparison between Filament Group's loadCSS and AJAX technologies

The loadCSS library developed by Filament Group is widely recognized as the standard for asynchronously loading CSS. Even Google recommends its use. However, instead of using this library, some suggest utilizing ajax to achieve the same result. For example ...

Is it possible to convert a string to a float using JavaScript within an HTML document and then calculate the square root?

Recently started learning JavaScript and facing an issue. I'm trying to create a program where the user inputs a number into a text box, clicks a button, and then an alert box displays the Square Root of their number. However, whenever the alert appea ...

Trouble fetching data for my controller in AngularJS using UI Router resolve

My attempts to inject a resolve object containing loaded data into my controller are resulting in an Unknown Provider error : Error message: Unknown provider: configServiceProvider <- configService Below is the code I am working with: StateProvider ...

Encountering issues with innerHTML displaying undefined results while trying to retrieve and showcase data from a database through the use

This is a sample script for fetching data from a database using AJAX. <!DOCTYPE html> <html> <head> <script type="text/javascript"> function loadJSON() { var data_file = "http://www.example.com/data/connect.php"; var xmlhttp; ...

Execute an Angular factory AJAX request with each change in route

I operate a factory where I utilize a function called getExpenseList that performs an ajax call to fetch data from the expense table. Currently, I have two routes set up - one for listing expenses and another for adding new expenses. However, whenever I n ...

Tips for adding color to the <td> element in an ejs file using nodeJS

I am looking to incorporate a color into my .ejs file. Here is the code snippet I am working with: <% resultList.forEach(function(item, index){ %> <tr> <td><%= item.function %></td> <td><%= item.value %>< ...

Updating an HTML Table with AJAX Technology

I'm struggling to figure out how to refresh an HTML table using AJAX. Since I'm not the website developer, I don't have access to the server-side information. I've been unable to find a way to reload the table on this specific page: I ...

Vue2Editor not displaying updated content following data retrieval from axios call

I've encountered an issue with my Vue component that uses Vue2Editor. Everything was working great until I tried to update the content using data from an async function. To troubleshoot, I tested updating text in a simple div. Here's a snippet ...

Exploring the best practices for loading state from local storage in VueJS/NuxtJS by leveraging the "useLocalStorage" utility

When attempting to utilize useLocalStorage from pinia, I am encountering an issue where the data in the store's state is not fetched from local storage and instead defaults to the default value. Below is the code snippet from my store method: import ...

Could you provide suggestions on how to update the content of an HTML tag within a Vue component?

I am new to Vue.js and struggling to grasp its concepts. I am interested in finding a way for my custom Vue component (UnorderedList) to manipulate the content within it. For example, if I have <p> tags inside my component like this : <UnorderedL ...

Every file downloaded through the iframe is automatically stored in a designated server folder

Is it possible for my website to have an iframe that enables users to browse the web, and when they click on a download button on any external website, the file can be saved directly to a specific folder on my server instead of their own computer? I'm ...

Storing Vuex updates for multiple tabs - Tips and tricks

I am encountering an issue with my Vue app that uses Vuex. When I have multiple tabs open, any changes made to the store in one tab do not reflect in the other. Is there a way to ensure that the store/data is synchronized instantly across all tabs? const ...

Obtaining a result from a switch statement

Here is a solution to populate the generated drop-down menu: $('dropdown_options').innerHTML = '&nbsp;'; jsonResponse.forEach(function(element){ $('dropdown_options').innerHTML += '<option value='+ elemen ...

Learn the process of transferring data from a page to a layout in NUXT

I am in the process of creating a basic website. The goal is to dynamically change the Navbar elements based on the data set in the navLayout within the page template. My plan is to pass this data to the layout and then utilize props to transmit it to the ...

Is it possible to utilize localStorage.getItem within Next.js while using redux toolkit?

While I successfully used localStorage.setItem() inside the redux toolkit slice, I encountered an issue when trying to use localStorage.getItem(). The error message "local storage is not defined" popped up, preventing me from accessing the stored data. imp ...

Issue with authentication and cross-origin resource sharing (CORS) when implementing Spring Boot, Spring Security, Vue.js,

Running on vue.js 3, Vite 4.0.2, axios 0.25.0, and spring boot (Starter 2.7.2). A backend has been created in spring boot while using vue.js3, vite, and axios for the UI. Now, I simply want to make a call to rest with axios. Before implementing these func ...

What could be causing my completed torrents to sometimes not be saved to my disk?

Currently, I am working on developing a small torrent client using electron and webtorrent. Although everything appears to be functioning correctly initially, there is an issue where sometimes the resulting files from a finished download are not being save ...