javascript date.js parsing and sorting an array of objects

I'm currently working on creating a JavaScript array of objects, utilizing date.js to parse dates, and then sorting that array using date.js compare methods. Below is a snippet of code that highlights the two issues I am facing.

Issue 1: How can I handle dates that cannot be parsed by date.js and provide a warning for them? Issue 2: What is the best way to sort an array of objects based on these dates? (with or without date.js)

I have a feeling that my approach may not be optimal, so I would appreciate any suggestions or ideas.

    <script type="text/javascript" src="depend/date.js"></script>

<script type="text/javascript">
var timedata = ["tomorrow", "today", "next thursday", "2012-08-02T04:00:00.000Z"]; // sample data
var myArrayOfObjects = [];

//Iterating through the timedata array
for(var row = 0; row < timedata.length; row++){     
    var cleanrow = true;

    // First issue, unable to parse the string "2012-08-02T04:00:00.000Z" with Date.parse(timestr) returning 0 
    // even though it was initially created using the .toISOString method as a test
    // Error: Ignoring row 3, could not parse this date: 2012-08-02T04:00:00.000Z
    if (Date.parse(timedata[row])){ 
        time =  Date.parse(timedata[row]);
        isoTime = time.toISOString();
    }else{
        console.log("Ignoring row " + row + ", could not parse this date: " + timedata[row]);
        cleanrow = false;
    }
    var xdata = "dummytestdata";
    var weight = "dummytestdata";
    if(cleanrow) {
        myArrayOfObjects.push({x: xdata, xytime: isoTime, weight: weight});
    }
}

// Second issue
// Error: TypeError: Date.parse(a.xytime) is null
myArrayOfObjects = myArrayOfObjects.sort(function(a,b){ return Date.parse(a.xytime).compareTo(Date.parse(b.xytime)); });

// Displaying the sorted objects by dates
for(var row = 0; row < myArrayOfObjects.length; row++) {
    console.log(myArrayOfObjects[row].xytime);
}
</script>

Answer №1

Just a few small details to consider:

It might be beneficial to declare time and isoTime in the var section instead of leaving them to magically appear without defined scoping.

var cleanrow = true, isoTime = null, time = null;

You could optimize the code by parsing timedata[row] only once and reusing the variable.

time = Date.parse(timedata[row])
if (time){ 
    isoTime = time.toISOString();

Have you thought about storing the date as an object property instead of converting it to a string? This way, you can use the date directly for sorting.

myArrayOfObjects.push({x: xdata, xytime: isoTime, weight: weight, realTime: time});
//...
myArrayOfObjects = myArrayOfObjects.sort(function(a,b){ return a.realTime.compareTo(b.realTime); });

Also, according to the Mozilla documentation, the sort method modifies the array in place rather than creating a new one.

myArrayOfObjects = myArrayOfObjects.sort(...
//should be just
myArrayOfObjects.sort(...

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

The functionality of Javascript is being compromised when utilizing ng-repeat

Just recently diving into the world of AngularJs while developing a website. I've successfully retrieved data from Rest services on a page, and used ng-repeat to display it. The issue arises when I have a regular javascript element on the page that i ...

Tips for retrieving the slug value in getStaticProps for invoking the API with the slug as a parameter

Content on the Page: import { useRouter } from "next/router"; export default function Daily({ data }) { let router = useRouter() const { slug } = router.query; return slug; } And display on the page 60d6180ea9284106a4fd8441 ...

Troubleshooting React Native in VS Code using Node shims

I recently started working on a React Native project using the Ignite CLI 2.0.0 default boilerplate, and I find myself in need of some dependencies from node-based packages. To address this, I created files named transformers.js, babel-transform.js, and r ...

Activate the text area message by clicking on the href link

I am currently working on customizing the intercom plugin for a WordPress site. My goal is to have a message triggered when a user clicks on a hyperlink, essentially simulating the enter key press in a textarea. Here is the code snippet that I am using: ...

I am experiencing difficulty with the color of my progress bar in Firefox

After successfully creating an interactive progress bar that works perfectly in Google Chrome and surprisingly also in Safari without vendor prefixes, I encountered a roadblock when testing it on Firefox. The progress bar color reverts back to the default ...

Angular directive ng-clickIs the directive in angular known as

I am struggling to understand why my ng-click function in my directive is not triggering the fooControls clickTest. Why isn't clickTest logging to the console? Is there a more efficient way to accomplish this? Custom Directive app.directive('fo ...

Is using canvas the best option for creating simple image animations with JavaScript?

I am currently working on a basic animation project using JavaScript. This animation involves switching between 13 different images per second to create movement. I have created two simple methods for implementing this animation. The first method involves ...

implement a jQuery loop to dynamically apply css styles

Attempting to utilize a jQuery loop to set a variable that will vary in each iteration through the loop. The plan is for this variable to be assigned to a css property. However, the issue arises where every css property containing the variable ends up with ...

The consistent failure of the 201 status node express API is causing major

I am currently working on creating an API using Express. However, when I receive a response from the server, it shows '201 created'. The issue arises when I attempt to make an HTTP request through promises and encounter a false interpretation of ...

Using Material-UI version 1, pass the outer index to the MenuItem component when clicked

Within my component, there is a Table that displays rows generated from a custom array of objects. In the last TableCell, I aim to include an icon button that, upon being clicked, opens a Menu containing various MenuItem actions (such as edit and delete). ...

Exploring audio analysis across different platforms using the power of the Web Audio API

Currently, I am in the process of developing an audio visualizer application using the web audio api and the three.js library. Utilizing the html5 element has been effective in extracting audio from local mp3 files or streaming mp3 files through the crea ...

Compatibility issues with jQuery observed in Firefox and Internet Explorer 11

Check out the code here: jsfiddle demo HTML CODE: <div class="first"> <!-- Part one --> <div class="acord_col"> <div class="img_class" id="exist_site"></div> <div class="intro_text"> </div> </div&g ...

Passing variables from AJAX response to PHP using a passthru function

In my PHP file, I have implemented a functionality where certain checkboxes are checked and upon clicking a button, a JavaScript file is triggered. The JavaScript code snippet used is as follows: $.ajax ({ type: "POST", url: "decisionExec.php", ...

Troubleshooting issues with calculator operators in JavaScript for beginners

As a beginner in JavaScript, I've taken on the challenge of building a calculator to enhance my skills. However, I'm having trouble getting the operator buttons (specifically the plus and equal buttons) to function properly. Can someone please as ...

How to manipulate dates using Angular 2's date pipe to add or subtract hours

I am encountering an issue with the new Angular 2 Date Pipe. My date value is as follows: let myDate = '2017-01-31T17:53:36' When I use the Date Pipe to format it in the view like this; {{myDate | date: 'dd/MM/yyyy HH:mm' }} It dis ...

AJAX request lacks the 'access-control-allow-origin' header

I'm currently integrating a weather API into my app to display real-time weather information. Although I've used this API before, I am now attempting to fetch the data asynchronously using AJAX to avoid full page reloads. Below is the JavaScrip ...

"Receive your share of the catch in a pop-up notification

Is there a way to determine if a user shared a result without using the social network's Javascript SDK? All sharing aspects (authorization, sharing, etc.) are done through popups on my domain. var popup = window.open('/api/share/' + servic ...

Storing data with jQuery

Looking to store objects in jQuery for events. Each event will have a date, title, and some text that needs to be stored in an array. Wondering if using a multi-dimensional array would be the best way to go so I can easily iterate through them with a count ...

Creating a Dynamic List using Flutter for JSON Data

Currently, I am grappling with handling intricate JSON data in Dart and facing challenges with creating objects without prior knowledge of their types. Although I am grateful for the suggestions provided, I find myself still puzzled. For instance, in the ...

Tips for maintaining previously accessed data when utilizing useQuery

I am currently working on incorporating a GET request using useQuery from the react-query library. Below is the relevant code snippet: import queryString from "query-string"; import { useRouter } from "next/router"; const { query } = ...