Enhance the JSON sorting functionality to accommodate the Date object in Javascript

Although this function functions properly with strings and numbers, it encounters problems when Date objects are involved due to the use of the === comparison operator.

function getDataCounted(objects, key) {
let ret = [];
let groups = objects
    .reduce((accumulator, element, index, array) => {
        if (accumulator.indexOf(element[key]) < 0 &&
            array.findIndex(elm => elm[key].getTime() === array[key].getTime()) < index)
            accumulator.push(element[key]);
        return accumulator;
    }, [])
    .forEach(group => {
        let count = 0;
        objects.forEach(object => {
            if (object[key] === group) {
                count++;
            }
        });
        ret.push([
            group,
            count
        ])
    });
ret.sort((a, b) => a[0] - b[0]);
return ret;
}

I attempted to address this by:

    let groups = objects
    .reduce((accumulator, element, index, array) => {
        if (element instanceof Date) {
            if (accumulator.indexOf(element[key]) < 0 //
                &&
                array.findIndex(elm => elm[key].getTime() === array[key].getTime()) < index)
                accumulator.push(element[key]);
            return accumulator;
        }
        if (accumulator.indexOf(element[key]) < 0 &&
            array.findIndex(elm => elm[key] === array[key]) < index)
            accumulator.push(element[key]);
        return accumulator;
    }, [])

However, it did not resolve the issue.

jsfiddle

Answer №1

Substitute

ret.sort((a, b) => a[0] - b[0]);

With the following code:

  ret.sort((a, b) => {
    if (a[0] instanceof Date) {
      return a[0].getTime() - b[0].getTime();
    }
    else {
      return a[0] - b[0];
    }
  });

Check out the updated jsfiddle

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

Steps for establishing a thread pool for workers

I have been exploring the experimental functionality of the worker threads module in Node.js. After reading through the official docs and various articles (although limited in number), I decided to create a simple example. This example involves spawning te ...

The JavaScript-generated form element will not be included in the data submitted through the POST method

While it may appear that this question has been asked before, my specific inquiry seems to be unique as I have not found a similar answer in other threads. Therefore, I am initiating a new discussion. My issue revolves around a form which contains a link ...

displaying li tag depending on the index value within angularjs

I have an HTML structure similar to the following: <div class="main"> <ul> <li ng-repeat='save in saves'> <h3>{{save.name}}</h3> <div > <ul> ...

Creating a Click Counter with jQuery 2.0.1/2.0.2: A Step-by-Step Guide

Currently in the process of creating a fundraising webpage for charity, I have chosen to display an animated rabbit making its way Around The World. My progress so far includes a non-looping gif that plays on click, with a limitation on how often it can b ...

Using JQuery to switch out images that do not have an ID or class assigned

Currently, I am using a Google Chrome Extension to apply an external theme to a website. Unfortunately, the logo on the site does not have an ID or class that can be used to call it. I am searching for a solution to replace it with a different image. My ...

What is the correct way to chain promises within Promise.all?

Essentially, I retrieve all the rows from a schedule table and then process each individual row. If the row is already in the command table, I skip it. Otherwise, I insert it. Within Promise.all(rows.map(function(row){ I have 2 chained promises: return ...

Update the value of a JSON array and store it in a HiddenField

In my hiddenfield in asp.net, I have the following JSON serialized value: text = "[{ "Element":"E001", "City":"Madrid", "Country":"Spain"}, { "Element":"E003", "City":"Paris", "Country":"Italy"}, { "Element":"A001", "City":"Pekin", "Country":"Chin ...

Ajax request received no data from API

I have been facing an issue with my code where I am posting an email on an API URL using an HTML form and PHP code with an Ajax call. However, the response I am getting is empty. I need to display this response on the same page below the form. I am sharing ...

What causes the Request.Params of IHttpHandler to be accurate on the initial call, but become null on the subsequent call?

My HTML/Javascript page utilizes a jQuery ajax call to communicate with a .NET ajax handler (.ASHX). The issue arises in subsequent calls where the parameters passed in the data object are unexpectedly NULL despite being correct during the first call. Her ...

Pixel information from previous canvas remains intact post resizing

I have crafted a canvas and loaded pixel data at specific locations using the following code snippet. let maskCanvas = document.createElement("canvas"); let patchWidth = 30; let patchHeight = 30; let scale = 3; maskCanvas.setAttribute("class", "mask"); ...

Describe a Typescript Interface Value as a collection of strings or any input provided as an argument

Uncertain if the question title is accurate - currently developing react components within a library that has specific predefined values for certain properties. However, additional values may need to be added on a per usage basis. So far, this setup is fun ...

What are the steps to kick off my React App once I've cloned it?

Currently grappling with deploying my app using Netlify, I encountered an issue after cloning the app onto my new computer. > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8afee5eee5e6e3f9fefcb8cabba4baa4ba">[email  ...

Why isn't v-model functioning properly in Vue?

In my current project involving an API, I encountered a problem. I utilized axios to fetch data from the API, which returned a JSON array. Each array item had a radio value that I appended to it. Despite attempting to use v-model to track changes in the ra ...

Generate a collection of div elements as child nodes

I'm working on a project where I have multiple rows with input fields. My goal is to create an array for each row that contains the values of the inputs. For example, if I have 3 rows and the values of 'input1' are 1, 'input2' are ...

When the button is clicked, verify the existence of the file, then display a message and undo

I encountered a situation where I needed to verify if a user tries to input data with the same date and same region again, they should receive a prompt alert. I attempted to achieve this using code in the backend, as shown below:- protected void btnSave ...

Differences in the way json.dump() behaves on Windows compared to Linux

After developing a Python script to extract data from a website in json form by leveraging the requests library, I save it to a json file. The code was tested on Windows and worked perfectly. However, upon transitioning to a Linux environment, running the ...

Tips for establishing a fixed point at which divs cease to shrink as the browser size decreases

There are numerous dynamically designed websites where divs or images shrink as the browser size decreases. A great example of this is http://en.wikipedia.org/wiki/Main_Page The div containing the text shrinks proportionally to the browser size until it ...

Issue with A-frame Raycaster not functioning properly; specifically need to determine intersection point with a-sky

I am currently attempting to determine the coordinates where the ray caster intersects with the a-sky element. However, I am facing two main issues: 1) The ray caster is not visible even after adding showline:true 2) The intersection listener is never ...

Employ gulp to compile typescript files

While following the angular 2 quick start guide, I noticed that they use a typescript compiler and include a tsconfig.json file. I wanted to find a way to incorporate gulp into this process, and it seems like there are methods available to make it work. Ho ...

Can you provide me with a variable that will give me the total size of the scrollbar?

How can I determine the maximum number of pixels scrolled on a webpage? I attempted using window.pageXOffset, but it only gives the current scrolled amount. I require the total size at all times. ...