Arranging JSON object in Javascript based on date (String)

I am currently working with a JSON object in JavaScript and my goal is to arrange the object based on dates in ascending order.

fileListObj[id] = date;

 output : "#HIDDEN ID": "16/12/2013"

What steps should I take to sort the object by the most recent date?

My expertise lies in PHP, so this task is slightly unfamiliar to me.

Answer №1

utilize moment.js library

fileListObj.sort(function(a,b) {
  return moment(b, 'DD/MM/YYYY').valueOf() - moment(a, 'DD/MM/YYYY').valueOf();
})

Answer №2

To start, it is important to develop or obtain a reliable date parser. Relying solely on Javascript's built-in Date object can be problematic when parsing raw strings (see this discussion on Stack Overflow).

Next, utilize the Array.prototype.sort() method:

function parseDate(input) {
    var parts = input.split('/');
    return new Date(parts[2], parts[1]-1, parts[0]);
}

function sortAsc(a,b)
    { return parseDate(a.date) > parseDate(b.date); }

function sortDesc(a,b)
    { return parseDate(a.date) < parseDate(b.date); }

list.sort(sortAsc);

Answer №3

Below is an example showcasing a sorted table containing dates in ISO format:

var dates = ["12/05/2012", "09/06/2011","09/11/2012"]
var sorted=[];
for(var i=0, i= dates.length;i++){
  var p = dates[i].split(/\D+/g);
  sorted[i]= new Date(p[2],p[1],p[0]);
}

alert(sorted.sort(function(a,b){return b-a}).join("\n"));

If you wish to maintain the same input format, utilize the following function:

function formatDate(d)
{
    date = new Date(d)
    var dd = date.getDate(); 
    var mm = date.getMonth()+1;
    var yyyy = date.getFullYear(); 
    if(dd<10){dd='0'+dd} 
    if(mm<10){mm='0'+mm};
    return d = dd+'/'+mm+'/'+yyyy
}
sorted.sort(function(a,b){return b-a})
formatSorted = []
for(var i=0; i<sorted.length; i++)
{
    formatSorted.push(formatDate(sorted[i]))
 }

alert(formatSorted.join("\n"));

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

A guide on setting up a basic HTML server with Express.js

I'm a beginner in node.js and I am trying to set up a basic express.js static file server, but I am facing some challenges. I installed express.js 4.2 globally using the following command: npm install -g express-generator In my httpsrv.js file, I ha ...

Is there a way to convert the following PHP code into JavaScript?

Hey, I'm currently in the process of converting a PHP application to handle billing even when there's no internet connection. To achieve this, I'm transitioning the PHP code to JavaScript. However, I've encountered a roadblock where my ...

Updating the Backbone.js model within a MySQL database

I am facing an issue with my model setup: var Car = Backbone.Model.extend({ url: "/save.php", defaults: { color: "red" } }); Upon document ready, I initialize a new instance of the model and save it: new volvo = new Car({color:"gree ...

Different methods for organizing an array of strings based on eslint/prettier

I possess an assortment of keys that I desire to sort in alphabetical order whenever I execute eslint --fix/prettier. My inference is that such a feature does not exist by default due to its potential impact on the code's behavior. Therefore, my quer ...

React Final Form - Validation with React

Question: I am facing an issue with react-final form error messages when using record-level validation. The FormFilterFields component includes the following field: Field Names: export const fieldNames = { password: "field.password" }; Field: ...

Filling in subfields using data from various collections (excluding references)

When attempting to populate subfields of a document that are not defined as references, I encounter an issue where mongoose consistently returns null when fetching the document and populating the fields. This seems to be a common problem with no clear sol ...

Disabling schemas in MongoDB for enhanced flexibility and customization

(I apologize in advance for any language errors) const mongoose = require('mongoose'); const Schema = mongoose.Schema; const date = new Date(); const blogSchema = new Schema({ header:{ type : String, required : true, ...

Issues with utilizing jQuery AJAX for form submissions

I am currently customizing a webpage to fit the specific requirements of a client using a template. The page contains two contact forms which are being validated and sent to a PHP file via AJAX. One of the forms is standard, while the other one has been mo ...

Limit the selection of 'pickable' attributes following selections in the picking function (TypeScript)

In the codebase I'm working on, I recently added a useful util function: const pick = <T extends object, P extends keyof T, R = Pick<T,P>>( obj: T, keys: P[] ): R => { if (!obj) return {} as R return keys.reduce((acc, key) => { re ...

pretending to make an ajax call using jQuery

To enhance the user experience of file upload, I have implemented a fake ajax request. When the user clicks submit, the form disappears, a loading graphic appears, and after a few seconds, the page refreshes to display the newly uploaded image. However, e ...

Having trouble parsing XML with JavaScript

I am currently attempting to parse an XML file using JavaScript for a school assignment, and I am required to use pure JavaScript without jQuery. I am able to retrieve one value successfully, but encountering issues with another. The problem lies within m ...

Warning: It is important for each child in a list to have a unique "key" prop in the render() function of React

After calling an API endpoint in my app.js, I save the data to a state and then render it. The data displays in the browser, but there's a warning on the console saying: Warning: Each child in a list should have a unique "key" prop.. Here's my a ...

What could be the reason for Google Maps producing a static map instead of a dynamic one?

Here is a snippet of code that showcases Google Map integration: <div class="col span_1_of_3 gMapHolder"> </div> Utilizing JQuery: $(document).ready(function () { alert($(".mapUse").text()); var k = $(".mapUse").text(); var embed ...

Is it possible to switch the background-image after a gif has finished loading?

I am currently using a GIF as a background image, but I would like it to show a static image until the GIF is fully loaded and ready to play. After reading several similar discussions, I understand that you can manipulate elements with JavaScript once the ...

Generate a fresh column using data from the preceding column

My data frame has a structure similar to the following (with additional columns): srcmacaddr dstmacaddr 00-11-2a-3b-4c-5d 22-33-6e-7f-8g-9h 22-33-6e-7f-8g-9h 00-11-2a-3b-4c-5d 00-11-2a-3b-4c-5d 00-99-5d-4c-3b-2a 00-99 ...

Managing Numerous Ajax Calls

Dealing with Multiple Ajax Requests I have implemented several Like Buttons on a single PHP Page, which trigger the same Ajax function when clicked to update the corresponding text from Like to Unlike. The current code works well for individual Like Butt ...

Checking for Internet Connectivity in Mobile HTML5

Is it possible to check for internet connectivity on a mobile device? Can websockets be utilized to ping a server and determine if the connection is available? I am feeling frustrated as I believed there was a ping function in websockets for client-side u ...

The initial return value of $(document).height may be inaccurate, but is accurate upon recalculation

I am working on implementing a pop-up screen and I would like to darken the background when it opens. Below is the Javascript code: $(document).on('click', '.item', function(){ $("#popUp").css("display" , "block"); ...

What is preventing the use of await in Node.js?

When I remove the await here, an error occurs. It's interesting how necessary it is even though this code snippet came from a how-to guide. const posts = await graph.fetch('523008607856853', 'posts', 5) https://i.sstatic.net/v9lk ...

You can install the precise version of a package as mentioned in package.json using npm

At this moment, executing the command npm install will download the latest versions of packages. Is there a way to install the exact versions specified in the package.json file? ...