What could be causing my Vue.js sorting array script to malfunction?

I'm encountering an issue with sorting the table by Date. The sort function used to determine the type of sorting no longer works, and I'm unsure why.

html:

<th @click = "sort('data_produktu')" class="date">Data</th>

data:

messages: [],
   currentSort:'data_produktu',
     currentSortDir:'asc',

methods:

sort: function(s){
    
  if(s === this.currentSort) {
    this.currentSortDir = this.currentSortDir==='asc'?'desc':'asc';
  }
  this.currentSort = s;
  console.log(this.messages);
}

computed:

sortedMessages:function() {
  return this.messages.sort((a,b) => {
    let modifier = 1;
    if(this.currentSortDir === 'desc') modifier = -1;
    if(a[this.currentSort] < b[this.currentSort]) return -1 * modifier;
    if(a[this.currentSort] > b[this.currentSort]) return 1 * modifier;
    return 0;
  });
}

Array(console.log output because Im fetching it from DB):

0: {id_komunikat: '4', data_produktu: '2022-08-12 20:05:30', tresc: 'Example info', typ: '2', status_komunikatu: '1', …}
1: {id_komunikat: '5', data_produktu: '2022-08-12 20:05:36', tresc: 'Example info', typ: '2', status_komunikatu: '1', …}
2: {id_komunikat: '6', data_produktu: '2022-08-12 20:05:39', tresc: 'Example info', typ: '2', status_komunikatu: '1', …}
3: {id_komunikat: '7', data_produktu: '2022-08-12 20:05:47', tresc: 'Example info', typ: '1', status_komunikatu: '1', …}

Answer №1

It appears that the variable data_produktu represents a date data type, which cannot be directly sorted using greater than > or less than < comparisons. Instead, timestamps must be used for sorting.

For example:

array.sort(function(a,b){
  return new Date(b) - new Date(a);
});

Answer №2

Upon inspection, the calculated function appears to be suspect. There is a potential risk of causing an infinite loop since this.messages is mutated in place by calling the method .sort(). It would be wise to modify it as follows:

sortedMessages:function() {
  //       use `.slice()` to clone first
  this.messages.slice().sort((a, b) => ...)

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

How is the server architecture typically designed in a node.js application?

Currently, I am developing a node.js application using socket.io and I'm seeking advice on how to structure the folders properly. The files that I have in my project include: Server.js package.json Additionally, I have: Client.js Index.html Incl ...

Utilize React JS to dynamically render JSON array of images onto a JSX page in React

state = { products: [ { img: "'./images/heartstud.jpg'", name: "Heart Earrings", price: "1.99", total: "3.98", count: 2, description: "Yellow Chimes Crystals from Classic Designer Gold Plated Styl ...

The pagination feature in React MUI DataGrid is malfunctioning

I am currently working with a datagrid and implementing server-side pagination. I have set a limit of 5 objects to be returned from the backend, and an offset variable to indicate from which index the next set of data should come. const handlePageChange = ...

How to enhance a class in JavaScript by adding a dynamic property

Within my code, I've defined a class which looks like this: class classA { id: number; name: string; constructor(data){ this.id = data?.id || 0; this.name = data?.name || ''; } } What I aim to do now is add ...

Is it possible to set up Vite/Rollup in a way that only triggers vue-tsc for dependencies that are utilized by the entrypoints?

Currently, I am in the process of upgrading my Vue 2 project to Vue 3 and have decided to migrate from the Vue CLI to Vite since it is now end of life. The upgrade has resulted in numerous breaking changes, requiring refactoring of most files in the /src f ...

Utilizing Next.js for dynamic routing with [[...slug.js]] allows for comprehensive URL handling and seamless 404 page display for links leading back to the homepage - a feature

In order to achieve a single dynamic route for handling all requests in this application, I have created a file called [[...slug]].js. Data loading is managed using getServerSideProps(), allowing for server-side rendering. Notably, there are no index.js fi ...

Leverage variables in Ajax to retrieve the data of an HTML element

Seeking assistance in converting multiple lines into a single for loop. var optie1 = ""; if($('#form #optie1_check').is(':checked')) { optie1 = $('#form #optie1_naam').val(); } var optie2 = ""; if($('#form #optie2_ch ...

Guide on using a pipe feature with varying arguments when the main function is called

I am delving into functional programming for the first time and have a query regarding using pipes. Imagine I have this particular function: const updateArray = R.curry((index, value, array) => Object.assign([], array, {[index]: v ...

Using " " to split a name into two lines is not being recognized

My issue involves the display of tab names in two lines within multiple tabs. You can view the demonstration here. I attempted to use the \n character while setting the tab name but it was not recognized. Any suggestions on how to achieve this? Here ...

Unexpected Quote Will Not Appear

My random quote generator is not functioning properly, it should display a different quote on each click of the button. My colleagues are also facing the same issue. It was working fine when implemented in JavaScript, but after converting all the syntax to ...

Virtual machines have encountered issues when attempting to utilize setTimeout within the browser with vm.runInNewContext

When running a JS script using the vm module in a browser, the following details are included: vm.runInNewContext(codeToEval, sandboxObject); Although interval methods like setTimeout and setInterval do not work, even when exposed in the sandboxObject cr ...

Using Mootools to call a class function from a bound CSS class may lead to an error stating that it is not a function

Utilizing Mootools 1.3.2 Here is the code snippet: var DNReportAbuse = new Class({ Extends: DNUserDialog, comment_id: null, container: null, initialize: function(classname) { var bindclass = $(document.body).getElements(classname); bindclass. ...

Navigate to a list item once Angular has finished rendering the element

I need to make sure the chat box automatically scrolls to the last message displayed. Here is how I am currently attempting this: akiRepair.controller("chatCtrl", ['$scope', function($scope){ ... var size = $scope.messages.length; var t ...

Attention: It is not possible to update the React state on a component that is not mounted. Please use the useEffect cleanup function

Can you assist with solving this issue? //ReviewProductDetail.jsx : Initially, the page was populated from this particular component import React, { useEffect, useState } from 'react'; import RatingCardProductDetail from '../../components ...

Eliminate the classes that were inserted through Jquery

I'm currently working on an accordion and I've encountered an issue with jQuery adding classes that I don't want. How can I prevent jQuery from adding certain classes? The code below is what I have, but for some reason, jQuery keeps adding t ...

Enhanced Slider Display featuring Multiple Posts for Improved Performance

My Sample Page features a slider that displays over 200 posts, each containing 5 images. However, the slider loads all the images at once, causing my page speed to be very slow. I am looking for an optimized way to display the slider without compromising l ...

Issue: Configuration Error - CKEditor5 cannot be loaded for extension in Vuejs

Hey everyone, I'm currently facing an issue. I'm trying to customize a build and everything works fine in the cloned ckeditor along with the sample.html file. However, when attempting to implement the customized build in Vue 2, I encounter an err ...

Switch between various components using multiple buttons in Next.js

I am in the process of creating a component that will display different components depending on which button the user selects. Here are the available “pages”: ` const navigation = [ { name: "EOQ", return: "<EOQgraph />" }, { nam ...

Resizing the Vue page to fit the viewport and using Flexbox to anchor the footer to the bottom

My Vue.js page structure consists of a navigation bar, main body content, and a footer: <template> <div class="flex_container"> <div class="container_navigation"> <nav-bar /> </div> < ...

Accessing clipboard contents upon button click using TypeScript

Seeking assistance with retrieving data from the clipboard in TypeScript after clicking on a button. Please provide guidance. Thank you! ...