Ways to organize an array of objects in JavaScript

I'm currently attempting to organize this JavaScript object array by the Planned Start

[{"EPRID":"123","AssetName":"AS1","Identifier":"","ID":"C399","Category":"blank","This_ID":"0023-E","Approval status":"Need More Information","Status":"initial","Phase":"Implementation","Planned Start Date":"10/31/2017","Planned End Date":"22/11/2017","Description":"as1 testing","Requestor":"bob","Comments":"test comment","Comment_Updated_By":"jim","Comment_Updated_Timestamp":"09/14/2017 08:00:55"},
{"EPRID":"321","AssetName":"AS3","Identifier":"C19","ID":null,"Category":"Normal Changes","This_ID":"0013-E","Approval status":null,"Status":"initial","Phase":"Implementation","Planned Start Date":"11/21/2016","Planned End Date":"12/12/2016","Description":"as3 testing","Requestor":"joe","Comments":null,"Comment_Updated_By":null,"Comment_Updated_Timestamp":null},
{"EPRID":"213","AssetName":"AS5","Identifier":"C113","ID":null,"Category":"Normal Changes","This_ID":"0143-E","Approval status":null,"Status":"initial","Phase":"Authorization","Planned Start Date":"11/05/2017","Planned End Date":"11/05/2017","Description":"as5 testing","Requestor":"john","Comments":null,"Comment_Updated_By":null,"Comment_Updated_Timestamp":null}]  

I've attempted the following:

rowObj.sort(function(a, b) {
        return a["Planned Start Date"] < b["Planned Start Date"];
});

Based on advice from 979256

I also experimented with using localeCompare(), but still haven't achieved my desired outcome.

Answer №1

Give this a shot:

rowObj.sort(function (a, b) {

   let startDateA=new Date(a["Planned Start Date"]);
   let startDateB=new Date(b["Planned Start Date"]);

   if (startDateA.getTime() > startDateB.getTime()) {
       return 1;
     }

   if (startDateA.getTime() < startDateB.getTime()) {
       return -1;
     }

    return 0;
});

console.log(rowObj);

Answer №2

In JavaScript, when sorting an array of dates stored as strings, it's important to first convert the strings to actual date objects in order to get a correct comparison.

rowObj.sort(function(a, b) {
    return new Date(a["Planned Start Date"]) < new Date(b["Planned Start Date"]);
});

Answer №3

To properly sort the compare values according to dates, make sure to convert them into date format and then assign a value of either 0, 1, or -1.

arr.sort(function(a,b){
   return new Date(a['Planned Start Date']) - new Date(b['Planned Start Date']);
});

If you want to reverse the order:

arr.sort(function(a,b){
   return new Date(b['Planned Start Date']) - new Date(a['Planned Start Date']);
});

For more information, check out this post: Sort Javascript Object Array By Date

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

MySQL and PHP for Sorting Data

I currently have my MySQL database on phpMyAdmin connected to a PHP script. It contains information about 50 NFL players and their stats from last year. I want to create a dropdown box that allows me to sort the players by different categories like Recep ...

Exploring the magic of the (!!!) operator in JavaScript!

The !! operator proves to be quite helpful when converting non-boolean data types into Boolean values, mainly for "True" conditions. However, when it comes to false conditions, is using !!! necessary? ...

Absence of loaders detected in a uniquely crafted npm package

Experiencing an issue with a private npm package loaded from a local git server for use in multiple react applications. When the package is loaded in the application, an error occurs: Error: Module parse failed: Unexpected token (22:6) You may need an app ...

Incorporate a personalized shuffle feature into the Timber/Twig framework

I'm trying to shuffle an array and I implemented the following filter in my functions.php file add_filter( 'timber/twig', function ( $twig ) { $twig->addFilter( new Timber\Twig_Filter( 'shuffle', function ( $ar ...

Tips for increasing a progress bar as data is being added to a database in PHP when a button is clicked

I attempted to implement this code but faced difficulties. Here is the code snippet I used : <script> $(document).ready(function(){ var $progressbar = $("#progressbar"); $progressbar.show(); $('#uploadForm').on ...

Manipulating the DOM of a parent element using AngularJS directives

As a newcomer to AngularJS, I've been researching how to manipulate the DOM in a directive. Most resources I've found focus on manipulating the directive's own DOM, but my goal is to manipulate the DOM outside of the directive. In my projec ...

Adjust the background hue within PNotify

I've integrated the Porto Admin Theme into my website, which can be found at This theme utilizes PNotify for notifications, available at: I'm looking to customize the notification colors in a light pastel scheme when choosing "Bootstrap 4" or B ...

JavaScript loops excessively

I am new to JavaScript and working on creating a simple application where users translate English words to French. My goal is to display the English word in a div, and have users enter the corresponding French word in an input field that is processed when ...

Ways to prevent duplication when mounting and updating a Vue component

Working on a Vue application, I have various form components that can either create a new record or edit an existing one. When a form is active, clicking on another record or the create button should replace or clear the form's contents. The issue ar ...

What is the best way to dynamically update a specific value within an object based on the current state in React/Next?

I have implemented a Context API where an object is set, and when the user clicks, the state changes. I need to update a specific value with the new state value. const initialState = { notification: false, setting: false, profile: false, } exp ...

Unable to retrieve the user ID from a Discord username using Discord JS

let string = `${args[1]} ${args[2]}` console.log(string) const idofuser = client.users.cache.find((u) => u.username === `${string}`).id I am facing an issue with DiscordJS where it says "cannot read property 'id' of undefined" when trying to ...

How can I access the parent function within module.exports?

Hello, I am having issues with this code because I am unable to access checkIf in order to set its property LengthIs. When I log whether this is equal to module.exports, it returns false. Upon further inspection, I also checked what this was and it retur ...

In Angular, iterate through each country and assign a value of 0 to any blank fields

My challenge is to dynamically generate empty objects with a value of 0 for each country in relation to all months. Check out my plunker example: http://plnkr.co/edit/6ZsMpdFXMvGHZR5Qbs0m?p=preview Currently, I only have data available for 2 months per co ...

Unable to locate any NativeScript modules for tns-core-module/ui

I'm working on a {N}-Application and facing an issue with importing Images from the tns-core-modules/ui/image module. Unfortunately, it seems that the target cannot be found within the tns-core-module. This is my code snippet: import * as ImageModul ...

Tips for making Ajax crawlable with jQuery

I want to create a crawlable AJAX feature using jQuery. I previously used jQuery Ajax on my website for searching, but nothing was indexed. Here is my new approach: <a href="www.example.com/page1" id="linkA">page 1</a> I display the results ...

Strange Behavior of ngIf and @Input in Angular 2

Despite console indicating false, NgIf appears to always evaluate as true. The issue stems from the component's HTML below: <product-component-tree itemSku="{{item.itemSku}}" selectable="false" classes="col-md-12 col-xs-12"></product-compo ...

Angular: What is the best way to pass usersearch-input data to a different component and use it to generate a list of search results?

Seeking assistance as a beginner in Angular, I am currently working on my first project with Angular 8 for the frontend of an application. The challenge I faced was creating an HTML page (...stuff/searches) where users can input search criteria to find sp ...

Is there a way to retrieve a collection of files with a particular file extension by utilizing node.js?

The fs package in Node.js provides a variety of methods for listing directories: fs.readdir(path, [callback]) - This asynchronous method reads the contents of a directory. The callback function receives two arguments (err, files), with files being an arra ...

My React project is unable to locate a file after I modified its extension from .js to .tsx

After using npx create-react-app my-app to start my React project and adding Typescript, I encountered an issue after converting one of my components to a .tsx file. The error message I received was: Module not found: Error: Can't resolve './cont ...

What causes the Number() function to increase the value of a number when the number's length exceeds 15 characters?

Every time I execute this code, the number that is returned seems to increase. Can someone please clarify why this happens? let numbers = [8, 5, 4, 9, 7, 6, 0, 2, 3, 1, 9, 7, 4] return Number(numbers.join('')) Result: 8549760231974 ...