Arranging JSON objects in an array based on date, with the ability to include a 13th month in the date format

I have a function that successfully sorts an array of JSON objects by date, but I need it to also accommodate the 13th month (salary).

module = {};
module.exports = [
    {
        "date": "01-2012"
    },
    {
        "date": "12-2011"
    },
    {
        "date": "01-2014"
    },
    {
        "date": "08-2015"
    },
    {
        "date": "13-2014"
    }
];

document.getElementById("exports").innerHTML = JSON.stringify( module.exports ) ;

function parseMyDate( date_value ) {
    return new Date( date_value.replace(/([0-9]{1,2})\-([0-9]{4})/, "$2-$1-01") );
}

module.exports.sort(function(a, b) {
    return parseMyDate( a.date ) - parseMyDate( b.date );
});


document.getElementById("sorted").innerHTML = JSON.stringify( module.exports ) ;
<h1>module.exports unsorted</h1>
<pre id="exports"></pre>

<h1>module.exports sorted</h1>
<pre id="sorted"></pre>

Is there a way to make this happen?

I am working in a node.js environment, so I could easily utilize a package that enhances dates, however, I haven't been able to find one.

Thank you.

Answer №1

After making some adjustments to the parseMydate function, I was able to enhance its capability to handle non-date inputs by converting them into an integer format YYYYMM for sorting purposes.

update: The function now successfully handles single digit months as well.

module = {};
module.exports = [{
  "date": "1-2012"
}, {
  "date": "12-2011"
}, {
  "date": "1-2014"
}, {
  "date": "8-2015"
}, {
  "date": "13-2014"
}];

document.getElementById("exports").innerHTML = JSON.stringify(module.exports);

function parseMyDate(date_value) {
  return date_value.replace(/([0-9]{1,2})\-([0-9]{4})/, function(m, a, b) {
    return parseInt(b, 10) * 100 + parseInt(a, 10);
  });
}

module.exports.sort(function(a, b) {
  return parseMyDate(a.date) - parseMyDate(b.date);
});


document.getElementById("sorted").innerHTML = JSON.stringify(module.exports);
<h1>module.exports unsorted</h1>
<pre id="exports"></pre>

<h1>module.exports sorted</h1>
<pre id="sorted"></pre>

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

Change the state of items in a React component to either disabled or active depending on the active items list retrieved from the API

Obtained from the API, I have a collection of buttons that are displayed for filtering: For instance: button2 button4 button5 Assuming there are a total of 5 buttons. button1 and button3 are supposed to be in a disabled or inactive state (appearing ...

Double Off-Canvas sidebars found on a single page

I am a beginner with HTML, CSS, JS, and Bootstrap and looking for guidance on how to bring my idea to life. My concept involves creating a webpage with two Off-Canvas Sidebars: First Sidebar located on the left side that is visible by default upon page ...

Choosing various files from separate directories within an HTML input type="file" element

Is there a way to select multiple files from various directories using the HTML input type="file" element? I have been searching for resources on how to do this without any luck. Are there any npm packages that can assist with achieving this functionalit ...

"Aligning the title of a table at the center using React material

I have integrated material-table into my react project and am facing an issue with centering the table title. Here is a live example on codesandbox: https://codesandbox.io/s/silly-hermann-6mfg4?file=/src/App.js I specifically want to center the title "A ...

Something is amiss with the PHP email validation functionality

I have been facing issues with the functionality of my form that uses radio buttons to display textboxes. I implemented a PHP script for email validation and redirection upon completion, but it doesn't seem to be functioning correctly. The error messa ...

Issue with data-ng-class function not being invoked

I'm currently working on a simple Angular project where I need to dynamically color list items based on a function called in data-ng-class. Below is an excerpt from my HTML file: <div> Rooms:<ul style="list-style:none;"> < ...

I'm not entirely sure why I keep getting the error message stating "Cannot read property 'innerHTML' of null"

Having an issue with my JavaScript code where I am trying to insert a new table row into the HTML but keep getting an error message that says "Uncaught TypeError: Cannot read property 'innerHTML' of null" <!DOCTYPE html> <html lang=" ...

The installation of package.json is unsuccessful, as it will only proceed with an empty name and version

Having trouble installing the package.json file after updating to the latest version of Node on my Windows PC. When trying to run npm, an error was thrown. Any help would be greatly appreciated. Command Prompt C:\Users\Felix\Desktop\ ...

Use CSS and JavaScript to create a visually appealing and interactive tree structure. Give the tree a dynamic design

I have been experimenting with CSS and JavaScript to create a dynamic graph based on a data table. You can view the graph that I need to replicate using CSS and JavaScript in this PDF. The example provided below showcases what I am attempting to achieve, a ...

Passing onClick event to parent component during iteration in ReactJS

I am facing a challenge where I need to remove a row from a table upon a click event. I have managed to create an iteration and display a delete button, but I am struggling with passing the onClick event from the parent component to the child component in ...

What is the best approach to changing the color of an item in a cart once it has been selected?

Recently, I've been facing an issue with changing the color of an item after it has been added to the cart. Below are my functions for adding and removing items from the cart: function addToCart(newItem) { cartItems.map(item => newItem.ty ...

Simple steps for Mocking an API call (Get Todos) using ComponentDidMount in React with Typescript, Jest, and Enzyme

About the application This application serves as a basic To Do List. It retrieves tasks from an API located at https://jsonplaceholder.typicode.com/todos?&_limit=5. Objective of the project The main goal is to test an API call that triggers ...

Issue with radio button click event not triggering

Whenever I click on a radio button, I want to call a function, but for some reason, it's not working as expected. I found this fiddle that demonstrates exactly what I want, but when I implement it in my code, it doesn't work. Here's a snipp ...

Exporting multiple modules in next.config.js allows for greater flexibility and customization

I am looking to include multiple modules in my next.config.js file. Currently, my file looks like this: const withImages = require('next-images') const path = require('path') module.exports = withImages({ esModule: false, }); Now ...

The REACT- Popover feature seems to be having trouble showing the data from my json file

Within the menu/ section, the names of my invited guests are not visible; only the InfoIcon is displayed in the cell. My goal is to implement a Popover feature that will show all the information about the invited guests (including their names and locations ...

What are the steps for configuring my Angular directive in this specific scenario?

Looking to create a directive that implements isolate scope. Here's the code snippet: angular.module('myApp').directive('itemCollection', ['$cookies', function($cookies) { return { restrict ...

Are these Java classes properly organized to efficiently map data from a JSON file?

Currently, I am in the process of translating a JSON file into Java code from a specific URL. It seems like a straightforward task. However, there seems to be an issue with the server returning null for certain key-values, which I will highlight below. I s ...

Identify all elements that include the designated text within an SVG element

I want to target all elements that have a specific text within an SVG tag. For example, you can use the following code snippet: [...document.querySelectorAll("*")].filter(e => e.childNodes && [...e.childNodes].find(n => n.nodeValue ...

Tips for creating a div that gracefully fades out its background image when hovered over, while keeping the internal content unaffected

I am looking to create a hover effect on a div element that has a background-color, background-image, and text. What I want is for the background-image to slowly disappear when the div is hovered over, while keeping the text and background color visible. I ...

What is the best way to showcase JSON API data in a comparison table?

Recently, I started working with react js and I have some JSON data that I would like to display in a comparison table as shown in the image below. I am not sure how to achieve this and here is the JSON API that I want to use in the table: . Also, here is ...