How to sort an array of objects with dates

I was looking for this question and no existing answer seems to apply. Consider the following:

[ { 'August 17th 2016': [75] }, // 75 is the length of the array which contains up to 75 objects ... { 'August 1st 2016': [5] }, { 'August 28th 2016': [5] }, ... ] 

What is the best way to sort the objects in this array by date and save the "English" representation of their key?

Note : The key is used as a chart label.

Everywhere I look at array.sort , but on the key of the created_at object.

The result should be:

 [ { 'August 1st 2016': [5] }, { 'August 17th 2016': [75] } { 'August 28th 2016': [5] }, ... ] 

Iโ€™m not sure how to act, so I have nothing to show.

+6
source share
2 answers

This can be done using date.parse on the object. I took the first key of the object, since there is apparently only 1 in each array entry. The tricky part is that date.parse does not work on โ€œ12thโ€ or โ€œ1stโ€, so we need to temporarily replace " th "or" st "on,. Thus, date.parse works with a string.

 var dates = [{ 'August 17th 2016': [75] }, { 'August 1st 2016': [5] }, { 'August 28th 2016': [5] }] const replaceOrdinals = o => { return Object.keys(o)[0].replace(/\w{2}( \d+$)/, ',$1'); } dates = dates.sort((a, b) => { return Date.parse(replaceOrdinals(a)) - Date.parse(replaceOrdinals(b)) }); console.log(dates); 

Keep in mind:

From @adeneo in the comments: date.parse depends on the implantation. You will probably want to read its documentation to determine if things like time zones will ruin things. As a more robust method, you can use something like moment.js to parse the date.

+6
source

The solution in Kevbot's answer is elegant, but its application is limited to ES6 browsers with a date.parse() implementation that matches the OP date format used.

Instead of adding a library such as moment.js to avoid the date.parse() dependency, an individual solution that will work in any JavaScript environment (including older browsers) can be executed with just a few lines of code:

 var dates = [ {'August 17th 2016': [75]}, {'August 1st 2016': [5]}, {'August 28th 2016': [5]} ]; dates.sort(function(a, b){ var i, j; for(i in a); //get datestring a for(j in b); //get datestring b; return MMMDDYYYYtoSortableNumber(i) - MMMDDYYYYtoSortableNumber(j); }); console.log(dates); // MMMDDYYYYtoSortableNumber() converts datestrings // such as "April 5th 1969" to 19690405. // Month name to digit approach adapted from // https://gist.github.com/atk/1053863 function MMMDDYYYYtoSortableNumber(datestring) { var mdy = datestring.match(/\w(\w\w)\D+(\d+)\D+(\d+)/); return mdy[3] * 10000 + ' anebarprayunulugepctovec'.search(mdy[1]) * 50 + mdy[2] * 1; } 

Note that it may be safer to represent datestrings as object values โ€‹โ€‹rather than object keys. Then they will be easier to remove safely (and faster for access). For instance.

 {label: 'August 17th 2016', data: [75]}, 
0
source

Source: https://habr.com/ru/post/1013075/


All Articles