{"id":1821,"date":"2024-02-22T13:00:00","date_gmt":"2024-02-22T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1821"},"modified":"2024-02-26T06:15:47","modified_gmt":"2024-02-26T06:15:47","slug":"sort-by-date-javascript","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/sort-by-date-javascript\/","title":{"rendered":"Sort an Object Array by Date in JavaScript (with code)"},"content":{"rendered":"\n<p>Sorting means putting things in order and making them more organized. We use dates in a lot of scenarios like building a task scheduler, managing events, or displaying a timeline. Therefore, often, we may be required to sort dates in JavaScript. In this article, we will explore how to sort an array of objects by date, allowing us to manage our data more accurately.\u00a0<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>How to Sort by Date in JavaScript?<\/strong><\/h2>\n\n\n\n<p><strong>JavaScript has a built-in Sort() method to sort data objects. A date in an object can be in the form of a string or as a Date object. <\/strong><\/p>\n\n\n\n<p>Here\u2019s the demonstration:<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-cff2ae3a432ecb370e151fbe3bdc3b7f\" style=\"background-color:#fedcba\"><code>const myObject = {\n  eventName: \"Sample Event\",\n  eventDate: \"2022-03-20\" \/\/ Date represented as a string\n};\n\nconst myObject = {\n  eventName: \"Sample Event\",\n  eventDate: new Date(\"2022-03-20\") \/\/ Date represented as a Date object\n};\n<\/code><\/pre>\n\n\n\n<p>Whether the date is initially stored as a string or as a Date object, We may often need to convert it into a Date object to perform various operations on it.<\/p>\n\n\n\n<p>Next, we will use a compareFunction inside the sort() method.\u00a0<\/p>\n\n\n\n<p>CompareFunction is written as :&nbsp;<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-afb9eb0390b7dec18c13044b8e37bcf4\" style=\"background-color:#fedcba\"><code>array.sort(compareFunction);<\/code><\/pre>\n\n\n\n<p>This compareFunction takes two parameters in it. Let it be a and b. These are the two values we are comparing. It returns a negative, zero, or positive value based on arguments passed.<\/p>\n\n\n\n<p>If \u2018a\u2019 should be placed before \u2018b\u2019 it returns a negative value, in the case of a positive value \u2018a\u2019 is placed after \u2018b\u2019, and zero is returned if \u2018a\u2019 and \u2018b\u2019 are of the same order.<\/p>\n\n\n\n<p>Let&#8217;s explore various methods for sorting dates in JavaScript.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1) Sort() Method with Date Objects<\/strong><\/h3>\n\n\n\n<p>This is a simple approach by using a built-in sort() method with Date objects. The sort() method compares Date objects directly and sorts the array in ascending order. Let\u2019s understand through an example to sort by date:\u00a0<\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-1b70fc6630c8baf2afcc4b342ab2a59d\" style=\"background-color:#fedcba\"><code>\/\/ Sample data representing employees with names and dates of joining\nconst employeesData = &#91;\n  { name: 'John Doe', joinDate: '2022-03-15' },\n  { name: 'Alice Smith', joinDate: '2023-01-10' },\n  { name: 'Bob Johnson', joinDate: '2022-06-22' }\n];\n<\/code><\/pre>\n\n\n\n<p>Here as we can see initially our dates are in string form, so we have to convert these to Date objects because the sort() Method works on Date objects.<\/p>\n\n\n\n<p>The syntax for creating a Date object is:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">let dateX = new Date(x.joinDate);\n\nHere a new Date() constructor is used. Let's apply this in our example:\n\n\/\/ Convert date strings to Date objects and then sort the array\nemployeesData.sort((a, b) =&gt; new Date(a.joinDate) - new Date(b.joinDate));\n\n\/\/ Display the sorted array based on the 'joinDate' property\nconsole.log(employeesData);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-87bec87b5a037c17d47f4bc84cd33b67\" style=\"background-color:#fedcba\"><code>&#91;\n  { name: 'John Doe', joinDate: '2022-03-15' },\n  { name: 'Bob Johnson', joinDate: '2022-06-22' },\n  { name: 'Alice Smith', joinDate: '2023-01-10' }\n]\n<\/code><\/pre>\n\n\n\n<p>Hence our dates are successfully sorted using the sort() method.<\/p>\n\n\n\n<p>we returned -1,1 or 0 based on comparisons. More appropriately we returned -1 if \u2018a\u2019 should be placed before \u2018b\u2019,1 if \u2018a\u2019 should be placed after \u2018b\u2019, and 0 if no change.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>2) Using getTime() Method<\/strong><\/h3>\n\n\n\n<p>In this method, sorting is done by numeric representations of dates. The numeric representations are obtained by the getTime() method. We will use the sort() method along with getTime() to sort dates. Let&#8217;s consider an example:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Sample data representing employees with names and dates of joining\nconst employeesData = [\n  { name: 'John Doe', joinDate: new Date('2022-03-15') },\n  { name: 'Alice Smith', joinDate: new Date('2023-01-10') },\n  { name: 'Bob Johnson', joinDate: new Date('2022-06-22') }\n];\n\n\/\/ Sorting the array based on the 'joinDate' property\nemployeesData.sort((a, b) =&gt; a.joinDate.getTime() - b.joinDate.getTime());\n\n\/\/ Display the sorted array based on the 'joinDate' property\nconsole.log(employeesData);<\/pre><\/div>\n\n\n\n<p>Here already our dates are as date objects. We got numeric representations by getTime() and then used a compareFunction inside sort() method.<\/p>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-609047ff70e352aa89f188ac1f42046b\" style=\"background-color:#fedcba\"><code>&#91;\n  { name: 'John Doe', joinDate: 2022-03-15T00:00:00.000Z },\n  { name: 'Bob Johnson', joinDate: 2022-06-22T00:00:00.000Z },\n  { name: 'Alice Smith', joinDate: 2023-01-10T00:00:00.000Z }\n]\n<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>3) Using a Custom Sorting Function<\/strong><\/h3>\n\n\n\n<p>In this approach, we will define a custom sorting function. We can design the function as we want, and then we will pass it as an argument for the sort() method.\u00a0<\/p>\n\n\n\n<p>Let&#8217;s take an example where we want to sort decreasingly by date:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;javascript&quot;,&quot;mime&quot;:&quot;text\/javascript&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;JavaScript&quot;,&quot;modeName&quot;:&quot;js&quot;}\">\/\/ Sample data representing employees with names and dates of joining\nconst employeesData = [\n  { name: 'John Doe', joinDate: new Date('2022-03-15') },\n  { name: 'Alice Smith', joinDate: new Date('2023-01-10') },\n  { name: 'Bob Johnson', joinDate: new Date('2022-06-22') }\n];\n\n\/\/ Custom sorting function for descending order\nconst sortByJoinDateDescending = (a, b) =&gt; {\n  return b.joinDate - a.joinDate;\n};\n\n\/\/ Sorting the array based on the 'joinDate' property in descending order\nemployeesData.sort(sortByJoinDateDescending);\n\n\/\/Display the output\nconsole.log(employeesData);<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background has-link-color wp-elements-e71ed2949f91f26ca7bc4e7b57a8c46f\" style=\"background-color:#fedcba\"><code>&#91;\n  { name: 'Alice Smith', joinDate: 2023-01-10T00:00:00.000Z },\n  { name: 'Bob Johnson', joinDate: 2022-06-22T00:00:00.000Z },\n  { name: 'John Doe', joinDate: 2022-03-15T00:00:00.000Z }\n]\n<\/code><\/pre>\n\n\n\n<p>Here we can see that we created our custom function sortByJoinDateDescending to sort in descending order. We returned b.joinDate &#8211; a.joinDate in the function, it simply reversed the logic that we used in the previous example.<\/p>\n\n\n\n<p>More appropriately we returned -1 if \u2018b\u2019 should be placed before \u2018a\u2019,1 if \u2018b\u2019 should be placed after \u2018a\u2019, and 0 if no change. Therefore by this method, we can create a separate function and then use it in the sort() method.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion<\/strong><\/h2>\n\n\n\n<p>Now we have learned how to sort an object by date property. In this article, we covered various methods such as using the built-in sort() method, the getTime() method, and also a custom sorting function. You can also learn <a href=\"https:\/\/favtutor.com\/articles\/sort-alphabetically-javascript\/\">how to sort alphabetically<\/a> because that is also a common scenario in the real world.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to sort an array of objects by date in JavaScript using various methods with examples to better understand them.<\/p>\n","protected":false},"author":13,"featured_media":1823,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[9],"tags":[11],"class_list":["post-1821","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-web-development","tag-javascript"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1821","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1821"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1821\/revisions"}],"predecessor-version":[{"id":1977,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1821\/revisions\/1977"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1823"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1821"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1821"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1821"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}