Sort JSON data based on Date and Time
You could use String#localeCompare
in a sort callback for the property start
, because ISO 8601 dates are sortable as string.
var array = [ { id: 1, start: "2016-12-07T13:00:00", subject: "test1" }, { id: 2, start: "2016-12-07T09:00:00", subject: "test2" }, { id: 3, start: "2016-12-07T10:00:00", subject: "test3" }, { id: 4, start: "2016-12-07T07:00:00", subject: "test4" }, { id: 5, start: "2016-12-07T14:00:00", subject: "test5" }];
array.sort(function (a, b) { return a.start.localeCompare(b.start);});
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
how to sort JSON by date?
You're creating the Date object with just the time which results in an invalid date. Use the date and the time to create your date object:
const newsArray = [ {date: '2018-11-17', time: '18:35:00'}, {date: '2018-11-17', time: '17:35:00'}, {date: '2018-11-17', time: '16:20:00'}, {date: '2018-11-17', time: '20:39:00'},];
const res = newsArray.sort((a, b) => new Date(b.date + ' ' + b.time).getTime() - new Date(a.date + ' ' + a.time).getTime()); console.log(res);
How do I sort a JSON by Date?
Here are a couple of errors I found in your code:
- Your function name has a typo, it should be
sortByDate
and notsortbyDate
. - You need top sort the inner json.Data.Contents array, not the outer json object.
- You need to reference the first element of your
lastUpdated
arrays usinglastUpdated[0]
. - Finally, you do not need to call
toJSON()
on the date objects in your sorting function, simply convert to date and return the difference.
Also your inner data fields are arrays, which seems strange for a Key
and a lastUpdated
value.
If you keep your fields as arrays, here is a working example showing how to sort the inner Data.Contents
array by date:
const jsonString = `{ "Data": { "Contents": [{ "Key": ["HelloTest"], "lastUpdated": ["2019-10-25T10:30:50.558Z"] }, { "Key": ["TestHello"], "lastUpdated": ["2019-03-26T10:30:50.558Z"] }] }}`;
function sortByDate(a, b) { return new Date(a.lastUpdated[0]) - new Date(b.lastUpdated[0]);}
const json = JSON.parse(jsonString);const defaultValue = { Data: { Contents: [] } };const sortedContents = [...(json || defaultValue).Data.Contents].sort(sortByDate);const output = { ...json, Data: { Contents: sortedContents } };
console.log(output);
sort JSON by date
Assuming that you have an array of javascript objects, just use a custom sort function:
function custom_sort(a, b) {
return new Date(a.lastUpdated).getTime() - new Date(b.lastUpdated).getTime();
}
var your_array = [
{lastUpdated: "2010/01/01"},
{lastUpdated: "2009/01/01"},
{lastUpdated: "2010/07/01"}
];
your_array.sort(custom_sort);
The Array sort
method sorts an array using a callback function that is passed pairs of elements in the array.
- If the return value is negative, the first argument (
a
in this case), will precede the second argument (b
) in the sorted array. - If the returned value is zero, their position with respect to each other remains unchanged.
- If the returned value is positive,
b
precedesa
in the sorted array.
You can read more on the sort
method here.
How to sort Json by date (newest to oldest)
You can use Array.sort()
function. Something like this:
(function() { var data = [{ "author": "some text", "title": "some text", "description": "some text", "image_big": "image link", "image_small": "image link", "date": "2015-06-17", "content": "some text some text some text some text some text", "category": "category", "subcategory": [ "some subcategory" ], "keywords": "keywords,keywords...", "id": "45654", "url": "article link" }, { "author": "some text 2", "title": "some text 2", "description": "some text 2", "image_big": "image link 2", "image_small": "image link 2", "date": "2015-06-20", "content": "some text some text some text some text some text", "category": "category", "subcategory": [ "some subcategory" ], "keywords": "keywords,keywords...", "id": "45654", "url": "article link" }];
console.log(data.sort(function(a, b) { return b.date > a.date; }));})();
Sort JSON array by date key
function comp(a, b) {
return new Date(a.result.date).getTime() - new Date(b.result.date).getTime();
}
your_array.sort(comp);
Just to extend @Karthikr's comment.
var result = [];
result.push({
id: 'ID',
result: {
url: 'test',
date: '15 May 2013, 6:40 pm'
}
}, {
id: 'ID',
result: {
url: 'test',
date: '20 Dec 2012, 8:00 am'
}
}, {
id: 'ID',
result: {
url: 'test',
date: '29 Jun 2012, 5:47 pm'
}
});
function comp(a, b) {
return new Date(a.result.date).getTime() - new Date(b.result.date).getTime();
}
result.sort(comp);
$('body').append(JSON.stringify(result));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
How to sort json data firstly by data and then by time?
If subtracting the two dates results in 0
(no difference), include the time in the equation. Something like:
var result = document.querySelector('#result');result.textContent = JSON.stringify(getData().sort(sortDateTime), null, ' ') + '\n\n**using sortDateTime2\n'+ JSON.stringify(getData().sort(sortDateTime2), null, ' ');
function sortDateTime(a, b) { var A = new Date(a.event_date); var B = new Date(b.event_date); if (A - B == 0) { // no difference, include event_time var tA = a.event_time.split(':'); var tB = b.event_time.split(':'); A.setHours( /pm/i.test(tA[1]) ? +tA[0]+12 : tA[0] ); A.setMinutes(+tA[1].replace(/[a-z]/gi, '')); B.setHours(/pm/i.test(tB[1]) ? +tB[0]+12 : tB[0]); B.setMinutes(+tB[1].replace(/[a-z]/gi, '')); } return A - B;}
// sorting on date/time using setTime helperfunction sortDateTime2(a, b) { return setTime(new Date(a.event_date), a.event_time) - setTime(new Date(b.event_date), b.event_time);}
// bonus: helper to set time from a time stringfunction setTime(thisDate, timeStr) { return new Date( [ [ thisDate.getFullYear(), thisDate.getMonth()+1, thisDate.getDate() ].join('/'), timeStr.replace(/(a|p)/, function (m) {return ' ' + m;} ) ] .join(' ') );}
function getData() { return [{ id: "xxxx", feed_id: "yyyy", title: "abcd ", detail: "efgh.", event_date: "Tue, 26 May 2015 00:00:00 +1000", event_time: "6:30pm", date: "Thu, 23 Apr 2015 23:05:04 +1000", expires_at: 1432634400, end_time: "8:00pm", timestamp: 1429794304 }, { id: "xxxx", feed_id: "yyyy", title: "abcd ", detail: "efgh.", event_date: "Tue, 26 May 2015 00:00:00 +1000", event_time: "4:30pm", date: "Thu, 23 Apr 2015 23:05:04 +1000", expires_at: 1432634400, end_time: "8:00pm", timestamp: 1429794304 }, { id: "xxxx", feed_id: "yyyy", title: "abcd ", detail: "efgh.", event_date: "Tue, 27 May 2015 00:00:00 +1000", event_time: "1:30pm", date: "Thu, 23 Apr 2015 23:05:04 +1000", expires_at: 1432634400, end_time: "8:00pm", timestamp: 1429794304 } ];}
<pre id="result"></pre>
Related Topics
How to Change Height in Mat-Form-Field
Prevent Form Submission on Enter Key Press
Reactjs: Expected Onclick Listener to Be a Function, Instead Got Type String
Destroy Chart.Js Bar Graph to Redraw Other Graph in Same <Canvas>
Parsing String as Json With Single Quotes
How to Push Array to Json Object in Angular
Get Array of Values from Multiple Inputs Using Jquery
Comparing Two Json Arrays and Get Not Matching Values
Onclick Event Not Working on Google Chrome
Displaying Navbar on Multiple HTML Pages Using Bootstrap
How to Sort Data in Ascending or Descending Order in Reactjs
Javascript Sum and Group by of Json Data
Remove Double Quotes from Array in Angularjs
How to Disable Button After (Click) in Angular
React Typescript Is Not Assignable to Parameter of Type
Background-Image in React Component