Sort Array by ISO 8601 date
Sort Lexicographically:
As @kdbanman points out, ISO8601See General principles was designed for lexicographical sort. As such the ISO8601 string representation can be sorted like any other string, and this will give the expected order.
'2007-01-17T08:00:00Z' < '2008-01-17T08:00:00Z' === true
So you would implement:
var myArray = [
{ name:'oldest', date:'2007-01-17T08:00:00Z' },
{ name:'newest', date:'2011-01-28T08:00:00Z' },
{ name:'old', date:'2009-11-25T08:00:00Z' }
];
myArray.sort(function(a, b) {
return (a.date < b.date) ? -1 : ((a.date > b.date) ? 1 : 0);
});
Sort using JavaScript Date:
Older versions of WebKit and Internet Explorer do not support ISO 8601 dates, so you have to make a compatible date. It is supported by FireFox, and modern WebKit though See here for more information about Date.parse support JavaScript: Which browsers support parsing of ISO-8601 Date String with Date.parse
Here is a very good article for creating a Javascript ISO 8601 compatible date, which you can then sort like regular javascript dates.
http://webcloud.se/log/JavaScript-and-ISO-8601/
Date.prototype.setISO8601 = function (string) {
var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
"(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
"(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
var d = string.match(new RegExp(regexp));
var offset = 0;
var date = new Date(d[1], 0, 1);
if (d[3]) { date.setMonth(d[3] - 1); }
if (d[5]) { date.setDate(d[5]); }
if (d[7]) { date.setHours(d[7]); }
if (d[8]) { date.setMinutes(d[8]); }
if (d[10]) { date.setSeconds(d[10]); }
if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
if (d[14]) {
offset = (Number(d[16]) * 60) + Number(d[17]);
offset *= ((d[15] == '-') ? 1 : -1);
}
offset -= date.getTimezoneOffset();
time = (Number(date) + (offset * 60 * 1000));
this.setTime(Number(time));
}
Usage:
console.log(myArray.sort(sortByDate));
function sortByDate( obj1, obj2 ) {
var date1 = (new Date()).setISO8601(obj1.date);
var date2 = (new Date()).setISO8601(obj2.date);
return date2 > date1 ? 1 : -1;
}
Updated usage to include sorting technique credit @nbrooks
Sort by iso string descending isn't working
iso_string
is in string type you need to convert it into date and then sort. Here is a improved sample
var dates = [{ "formatted_date": "22/09/2018 @ 04:02pm", "iso_string": "2018-09-22T06:02:22.485Z"}, { "formatted_date": "22/09/2018 @ 04:12pm", "iso_string": "2018-09-22T06:12:04.471Z"}, { "formatted_date": "22/09/2018 @ 04:05pm", "iso_string": "2018-09-22T06:05:45.818Z"}, { "formatted_date": "22/09/2018 @ 04:00pm", "iso_string": "2018-09-22T06:00:46.954Z"}, { "formatted_date": "22/09/2018 @ 03:56pm", "iso_string": "2018-09-22T05:56:13.968Z"}];var sorted_dates = dates.sort(function(a, b) { return new Date(b.iso_string) - new Date(a.iso_string);});console.log(sorted_dates);
How to sort array that has nested objects with ISO date
You can use Date
as follows:
const info = [ { "userID" : "aaa", "dob" : "2021-07-23 22:30:00.000Z" }, { "userID" : "aaa11", "dob" : "2021-06-10 12:30:00.000Z" }, { "userID" : "aaa22", "dob" : "2021-09-23 22:30:00.000Z" } ];
const sorted = info.sort(({ dob: a }, { dob: b }) => new Date(a) - new Date(b));
console.log(sorted);
Sort ISO 8601 dates forward or backwards
It depends on whether or not you're mixing formats.
Within any specific format, like yyyy-mm-dd
or yyyy-Www-d
, ISO 8601 is built to sort lexicographically (other than negative years).
From the ISO 8601 wikipedia page:
Date and time values are organised from the most to the least significant: year, month (or week), day, hour, minute, second, and fraction of second. The lexicographical order of the representation thus corresponds to chronological order, except for date representations involving negative years. This allows dates to be naturally sorted by, for example, file systems.
That means that string sorting should work okay.
It's only if you mix formats will that not work. If that's the case, you'll need to convert to a specific format before comparing. By that, I mean something like converting all formats into yyyy-mm-dd
before comparison and then back afterwards if desired.
For example, if you have the input data:
2010-03-01
2010-W01-1
you could first change them all to:
2010-03-01:2010-03-01
2010-01-04:2010-W01-1
(prefixing the actual data with a specific form) then sort that. Once sorted, you then go back and strip off everything up to the first :
character in each element, which will recover the original form.
Not necessarily the most efficient way but you'll need to do something like that if you want to preserve the original form. If that's not an issue, simply convert them to the specific form once and leave them like that.
Sorting PHP Array by ISO Date
You can implement any sorting technique you can think of if you wrap it in a callback and use usort()
docs here
inside your callback, you can use strtotime or similar, and do simple int comparisons.
$myDateSort = function($obj1, $obj2) {
$date1 = strtotime($obj1->startTime);
$date2 = strtotime($obj2->startTime);
return $date1 - $date2; // if date1 is earlier, this will be negative
}
usort($myArray, $myDateSort);
Filter an array of ISO date by days of the week in javascript
An algorithm is:
- Sort the data by the value of the time property
- Find the index of the first day on the same date as the start date
- If an element is found, push that element into an array
- Increment the search date by 1 day
A lexical sort is used to sort on time and to find the records to return as it's an ISO 8601 string. Conversion to Date objects will work too but that seems unnecessary.
To select each date, dStart is set to the start of the UTC day and dEnd is set to the end of the UTC day. If no date is found in that range, none is added to the array. This prevents the case of a multi day gap in the data producing multiple entries of the same object (i.e. the first one after the gap) in the selected array.
If this should be based on local dates, then use setHours instead of setUTCHours.
/* Given data as an array of objects, return
* first on date plus first on next n days
* Dates are UTC, not local
*/
function getFirstNDays(data, n = 1, date = new Date()) {
// Make sure n is a positive integer
if (n % 1 || n < 0) return;
data.sort((a, b) => a.time.localeCompare(b.time));
let dStart = new Date(date);
dStart.setUTCHours(0,0,0,0);
let dEnd = new Date(dStart);
dEnd.setUTCHours(23,59,59,999);
let selected = [];
while (n--) {
let index = data.findIndex(obj => obj.time >= dStart.toISOString() && obj.time <= dEnd.toISOString());
// If record found, add to selected array
if (index != -1) {
selected.push(data[index]);
}
dStart.setUTCDate(dStart.getUTCDate() + 1);
dEnd.setUTCDate(dEnd.getUTCDate() + 1);
}
// Return selected values
return selected;
}
let daysdata = [
{time: '2022-01-20T11:00:00Z', data: {}},
{time: '2022-01-23T11:00:00Z', data: {}},
{time: '2022-01-23T12:00:00Z', data: {}},
{time: '2022-01-24T11:00:00Z', data: {}},
{time: '2022-01-24T12:00:00Z', data: {}},
{time: '2022-01-24T17:00:00Z', data: {}},
{time: '2022-01-24T23:00:00Z', data: {}},
{time: '2022-01-25T00:00:00Z', data: {}},
{time: '2022-01-25T04:00:00Z', data: {}},
{time: '2022-01-25T05:00:00Z', data: {}},
{time: '2022-01-25T06:00:00Z', data: {}},
{time: '2022-01-25T07:00:00Z', data: {}},
{time: '2022-01-25T14:00:00Z', data: {}},
{time: '2022-01-25T15:00:00Z', data: {}},
{time: '2022-01-26T13:00:00Z', data: {}},
{time: '2022-01-26T14:00:00Z', data: {}},
{time: '2022-01-26T15:00:00Z', data: {}},
{time: '2022-01-27T13:00:00Z', data: {}},
{time: '2022-01-27T14:00:00Z', data: {}},
{time: '2022-01-27T15:00:00Z', data: {}},
{time: '2022-01-28T14:00:00Z', data: {}},
{time: '2022-01-28T15:00:00Z', data: {}},
{time: '2022-01-28T16:00:00Z', data: {}},
{time: '2022-01-29T18:00:00Z', data: {}},
{time: '2022-01-29T19:00:00Z', data: {}},
{time: '2022-01-30T08:00:00Z', data: {}},
{time: '2022-01-30T09:00:00Z', data: {}},
{time: '2022-01-30T10:00:00Z', data: {}},
{time: '2022-01-30T11:00:00Z', data: {}},
];
console.log(getFirstNDays(daysdata, 7, new Date(Date.UTC(2022,0,23))));
Sort JavaScript nested object by ISOString date
The following will sort the clinics by start time in ascending order.
- It works by first converting the object property values into an array using
Object.values()
. - The values are sorted into ascending order using
Array.prototype.sort()
. - Finally a new object is created using
Array.prototype.reduce()
.
const clinics = { "a0CW00000027OX3MAM": { "id": "a0CW00000027OX3MAM", "companyName": "Hendrick Medical Center", "startTime": "2018-08-10T05:30:00.000Z", }, "a0CW00000026gjJMAQ": { "id": "a0CW00000026gjJMAQ", "companyName": "ABC Manufacturing", "startTime": "2018-08-10T10:36:00.000Z", }, "a0CW00000026gipMAA": { "id": "a0CW00000026gipMAA", "companyName": "ABC Manufacturing", "startTime": "2018-08-01T10:36:00.000Z", }};
const sorted = Object.values(clinics) .sort((a, b) => a.startTime > b.startTime) .reduce((m, c) => m.set(c.id, c), new Map());
for (let [key, value] of sorted.entries()) { console.log(key, value);}
Sorting a string date array in TypeScript
Unless I am missing something, you can just directly convert to Date
without splitting?
this.filteredMovies.sort(function(a, b) {
return new Date(a.dateWatched) > new Date(b.dateWatched);
});
How to sort array by date In JavaScript?
Parse strings to get Date objects, then sort by compare function.
var a = [
{
"name": "February",
"plantingDate": "2018-02-04T17:00:00.000Z",
},
{
"name": "March",
"plantingDate": "2018-03-04T17:00:00.000Z",
},
{
"name": "January",
"plantingDate": "2018-01-17T17:00:00.000Z",
}
]
a.sort(function(a,b){
return new Date(a.plantingDate) - new Date(b.plantingDate)
})
console.log(a)
How to sort array by date?
You already have the dates formatted in a manner suitable for sorting. So we can write a trivial sorter for them:
const sortByDate = (data) =>
data .sort (({date: a}, {date: b}) => a < b ? -1 : a > b ? 1 : 0)
const data = [{date: "2022-05-10 13:36:00", open: 155.535, low: 155.4, high: 155.67, close: 155.44}, {date: "2022-05-10 13:35:00", open: 155.23, low: 155.2102, high: 155.62, close: 155.53}, {date: "2022-05-10 13:34:00", open: 154.97, low: 154.96, high: 155.29, close: 155.22}]
console .log (sortByDate (data))
.as-console-wrapper {max-height: 100% !important; top: 0}
Related Topics
Triggering a JavaScript Click() Event at Specific Coordinates
How to Check Whether <Ng-Content> Is Empty? (In Angular 2+ Till Now)
Dynamically Update Values of a Chartjs Chart
How to Round a Number in JavaScript? .Tofixed() Returns a String
How to Convert JSON Object to JavaScript Array
What's the Difference Between JavaScript and Jscript
Event Delegation VS Direct Binding When Adding Complex Elements to a Page
How to Copy JavaScript Object to New Variable Not by Reference
Truncate (Not Round Off) Decimal Numbers in JavaScript
Differencebetween Typeof and Instanceof and When Should One Be Used VS. the Other
How to Reset <Input Type = "File">
How to Iterate (Keys, Values) in JavaScript
Window.Print() Not Working in Ie
Jquery Function to Get All Unique Elements from an Array
Getting Error "Form Submission Canceled Because the Form Is Not Connected"
How to Check If the React Component Is Unmounted
Remove All Special Characters Except Space from a String Using JavaScript