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

Navigating through a JavaScript object array within another object

I am looking to iterate through a JavaScript object array Here is my object response: { "kind": "calendar#events", "etag": "\"p3288namrojte20g\"", "summary": "pedicura", "updated": "2019-05-01T14:25:51.642Z", "timeZone": "America/Argentina ...

Tips for controlling numerous tabSlideOUt tabs on a single webpage

Is there a way to implement multiple tabSlideOut functionalities on a single page, similar to the examples provided in the following links: source code on GitHub and Fiddle Example? Specifically, I am looking to have tabs that can be toggled, ensuring tha ...

Stopping the ability to navigate within an Ionic application

I am attempting to block navigation and display a popup in a controller. $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { if(someConditionMet) { event.preventDefault(); showPopup(); } } ...

What could be causing the background image on my element to not update?

I'm attempting to utilize a single background image that is 3 pixels wide and 89 pixels tall. Each vertical stripe of 1 pixel will serve as the background for a different div. I had presumed that adjusting the background-position by -1px 0 and specif ...

Generating a hierarchical structure of JSON data through iterative looping

Currently, I am in the process of creating a directive within Angular to assist with field validation. The functionality is working smoothly until it comes time to store the validation result. My objective is to store this information in an object structu ...

Troubleshooting: React.js State not updating properly on forms

New to React and facing a challenge with changing the state of form inputs. Here's what I'm trying to do: constructor(props) { super(props); this.state = { pwd:'', email:'', value:'' ...

Despite population, MongooseJS still renders blank array

Currently in the process of developing an application using Node.js with MongooseJS as the middleware for handling database operations. Encountering an issue with nested schemas, specifically with one of them being populated incorrectly. Despite tracking ...

What are the steps to establish a Z-axis coordinate system in three.js?

When working with three.js, the Y axis typically represents up and down, while the Z axis represents forward and backward. However, I want to switch this so that the Z axis represents up and down, and the Y axis represents forward and backward. Here is an ...

What is the best way to showcase saved HTML content within an HTML page?

I have some HTML data that was saved from a text editor, <p style=\"font-size: 14px;text-align: justify;\"> <a href=\"https://www.xpertdox.com/disease-description/Chronic%20Kidney%20Disease\" style=\"background-color: tr ...

Using the class method to handle jQuery events alters the context

Is it possible to access the class context from within a method being used as a jQuery event handler? The example below illustrates the scenario: class EventHandler { constructor() { this.msg = 'I am the event handler'; } ...

A warning message has been triggered: 'Script Alert Error - Object

I've been putting in hours on a SUP project that requires some tweaking and I keep running into the issue Script Alert Error: Object expected The code I've added is: $('#bottomOfStart_ScreenForm').before('<div style="display: ...

Looking to retrieve the raw HTTP header string in Node.js using express.js?

Currently, I am utilizing Node.js and express.js for my work. The project I am currently working on requires me to access the raw strings of the HTTP headers (charset and accepted). In express.js, there is a function available that can provide the charset ...

What methods can be used to extend the distance measurement with the help of Google Maps

I've searched online for the answer, but still haven't found it. I'm currently developing a website where users can search and select a location using the Google Geocoding API. Once the user chooses a place, I retrieve its bounds, but then ...

What is the best way to showcase just 5 photos while also incorporating a "load more" function with

Is there a way to display only 5 images from a list on the first load, and then show all images when the user clicks on "load more"? Here is the code I have: $('.photos-list').hide(); $('.photos-list').slice(1, 5).show(); $ ...

Blurry text and icons in Bootstrap 3

Does anyone else notice a strange display issue with Bootstrap 3 fonts and glyphicons? It seems like the bitmaps and fonts are appearing blurry on desktops when using Firefox and Chrome, but everything looks fine on mobile devices. I've attached an ex ...

Can Self-Invoking Functions, Resharper 6.1, and JS Lint all Play Nice Together?

Consider this piece of JavaScript code: MyCompany.MyProduct = {}; (function () { "use strict"; MyCompany.MyProduct.doSomethingAmazing = function () { }; }()); This approach is acceptable and passes Mr Crockford's JavaScript lint. Howe ...

Send data from the URL to PHP and then to Javascript in order to showcase the value within an input field

I need to pre-fill an email subscriber form with an email address from the URL. The specific email address is included in the following URL: http://www.domain.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcacbdbbb9e3b9b ...

Transforming seconds into years, months, weeks, days, hours, minutes, and seconds

Can anyone help me modify Andris’ solution from this post: Convert seconds to days, hours, minutes and seconds to also include years, months, and weeks? I am currently running this code: getDateStrings() { console.log(req_creation_date); const toda ...

What's the most efficient way to iterate through this Array and display its contents in HTML?

I'm struggling to sort a simple array and I think the issue might be related to the time format. I'm not sure how to reference it or how I can properly sort the time in this array format for future sorting. //function defined to input values ...

Three.js - implementing a billboard effect that preserves orientation through camera pans

My situation involves a plane geometry that always faces the camera using the following line of code in the update loop: plane.lookAt(camera.position); While I am utilizing OrbitControls to manipulate the camera, the plane successfully maintains its orie ...