Sorting JavaScript Objects By Date

My goal is to arrange my array of objects with date values in descending and ascending order.

Here is the code I am using:

function comp(a, b) {
  return new Date(a.jsDate) - new Date(b.jsDate);
}

function compNewestFirst(a, b) {
  return new Date(b.jsDate) - new Date(a.jsDate);
}

It is important to note that the JS Date format is valid for the new Date() method.

Although I am able to sort it in ascending order, I am facing issues with sorting it in descending order. I have attempted the following:

return new Date(b.jsDate) + new Date(a.jsDate);

Currently, I am unable to sort by the newest date first, as it only works in the oldest date first scenario.

Thank you.

Answer №1

Give it a shot:

function sortDatesDescending(a, b) {
  return new Date(b.date).getTime() - new Date(a.date).getTime();
}

Executing this function will result in a negative number which allows for ordering.

Feel free to experiment with this code on FIDDLE;

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

Deleting an element in an Array of objects using Typescript

export class AppComponent implements OnInit { title = 'bucketList'; bucketList: BucketListItem[] = [ new BucketListItem( "Goa Trip", "Travel to Goa" ) ]; ngOnInit() { } onItemAdded(eventData) ...

incorrect implementation of react lifecycle phases

My Sharepoint Framework webpart includes a property side bar where I can choose a Sharepoint List, and it will display the list items from that list in an Office UI DetailsList Component. Although all REST calls are functioning properly during debugging, ...

Incorporating external CSS and JS files into your WordPress website

Hello, I am unfamiliar with the Wordpress framework and I am seeking guidance on how to add an external CSS and JS file to my Wordpress page. I have successfully created a new page, but would like to incorporate a CSS and JS file into it. Would creating a ...

AngularJS form submission with and without page refresh

Looking to implement an AngularJS form directive where, if on /home page, redirect to /search/term and if already on /search page, submit without refreshing the page by simply changing the location. I am able to do both separately, but struggling to writ ...

The trim() method in Vue.JS does not properly handle trimming a passed string

I've been attempting to eliminate white space from a property of one of the returned objects using the .trim() function, but it's not working as expected. Even after trying JavaScript functions like .replace(/\s/g,''), the issue p ...

Discovering which chip has wrapped to the next line in Material UI Autocomplete can be found by closely inspect

Currently, I am working with a Material UI autocomplete feature that functions as follows: https://i.sstatic.net/4LrwI.png My goal is to determine when the fourth chip wraps to the next line within the autocomplete so that I can proceed with additional c ...

Tips for updating the state of an individual component in ReactJS without having to re-render the entire component

As a beginner in ReactJS, I am seeking guidance on how to modify the state of a specific component that was created within a Map function. Imagine I have a basic component named panels, with multiple panel-items. Each panel-item is essentially one componen ...

Is it possible to incorporate knockout.js within a Node.js environment by utilizing .fn extensions in custom modules?

I'm currently exploring the possibility of implementing the knockout.mapping.merge library in node.js, but I seem to be facing a challenge when it comes to extending ko objects within the module's scope. I am struggling to figure out how to exten ...

What is the method for striking through a line in a table?

I developed a unique jQuery script: <script type="text/javascript"> $(document).ready(function () { $('tr.inactive').each(function (index) { var tr = $(this); tr.find('td:first').after(function ...

Alter the component and then refresh it

I am encountering an issue with a component that has an event handler for a "like" icon. The goal is to allow users to click the like icon, update the database to indicate their liking of the item, and then re-render the component to visually reflect this ...

Dealing with a throw er; uncaught 'err' event while configuring a server with nodemon

I am currently in the process of setting up my local server using node.js and nodemon. Initially, everything runs smoothly on localhost, but as soon as I refresh the page or navigate to another page, the server crashes with an 'unhandled error event&a ...

The functionality of Jquery ceases to work once a setTimeout function is implemented

I need some help getting a series of functions to be delayed by 2 seconds using setTimeout. For some reason, whenever I try to implement this, the code stops executing altogether. I've double-checked the syntax and everything seems fine because it wor ...

Attempting to retrieve access token for Paylocity Web API in Node.js, encountering the issue of receiving an "invalid_client" error message

I've been attempting to retrieve the access token for the paylocity API. I can successfully obtain it through postman using the client id and client secret, but when I try to do so with Node.js, I receive the message {"error":"invalid_client"}. Below ...

Prevent the onscroll animation of the SVG from activating immediately upon its appearance on the screen

I am in the process of building a website that incorporates SVG technology. My issue is with some SVG icons that have animated effects when scrolling, but the animation triggers as soon as they come into view. What I really need is for these icons to sta ...

Creating a unique Voronoi Diagram wrap

I am currently working on the creation of a fantasy-style map that is procedurally generated using the cells of a Voronoi diagram to determine different terrains. While working on the tectonic plate generation, I came to the realization that having wrappi ...

The gridOptions.$gridScope.columns in ng-grid is modified two times when hiding or showing columns

Question: Why does the $scope.$watch function get called twice when I manually hide/show a column but only once when I reorder/sort columns in ng-grid? When I specifically target a single column with the watch function, it is only called once. I suspect ...

Looping through JSON keys using ng-repeat in AngularJS

I am currently working on a project where I need to populate some JSON data retrieved from the Google Tag Manager API and then send this information to the frontend which is developed in AngularJS. At the moment, I am utilizing ng-repeat on a card compone ...

Error Encountered: Unable to utilize $(...).mask function with jQuery in ASP.NET using C#

I have encountered an issue while working on a task involving jQuery masked for date. When running the task in HTML, it works perfectly fine. However, when attempting to run it in ASP.NET, I face the problem where 'mask is not a function'. Below ...

Unveiling the magic: Dynamically displaying or concealing fields in Angular Reactive forms based on conditions

In my current scenario, there are three types of users: 1. Admin with 3 fields: email, firstname, lastname. 2. Employee with 4 fields: email, firstname, lastname, contact. 3. Front Office with 5 fields: email, firstname, lastname, airline details, vendo ...

Utilize Bootstrap button dropdown to automatically assign a selected value to a list item

I have a form with a select box that transforms into a bootstrap button after the page loads. However, I am unable to set the selected value for the converted bootstrap button drop-down li. <button type="button" class="btn dropdown-toggle btn-default" ...