Typescript sort by date | Typescript sort array by date - SPGuides (2024)

Do you want to know about Typescript sort by date? This Typescript tutorial explains how to sort by date in Typescript. We will mainly focus on “sort array by date Typescript.”

To sort an array by date in TypeScript, first convert the date strings to Date objects, then use the sort() method with a custom comparator that compares dates using the getTime() method. Finally, if needed, convert the sorted Date objects back to strings. This approach ensures accurate sorting of dates, even when they are initially represented as strings.

Table of Contents

Typescript sort by date

Let us see how to sort dates in TypeScript with practical examples.

TypeScript, like JavaScript, has a built-in Date object that represents a single moment in time. Date objects can be compared, which is fundamental for sorting operations.

In TypeScript, you create a Date object by:

let date = new Date();

You can also create a Date object with a specific date in Typescript.

let specificDate = new Date('2025-01-01');

Here is an example of a Typescript sort by date. We can sort arrays by date using the sort method in typescript.

const dates: Date[] = [ new Date('2023-11-25'), new Date('2023-01-01'), new Date('2023-07-15') ]; dates.sort((a, b) => a.getTime() - b.getTime()); console.log(dates);

Output:

[ 2023-01-01T00:00:00.000Z, 2023-07-15T00:00:00.000Z, 2023-11-25T00:00:00.000Z]
Typescript sort by date | Typescript sort array by date - SPGuides (1)

This is an example of “typescript sort dates“.

See also throw Keyword in Typescript

sort array by date Typescript

Now, let us see how to sort an array by date in Typescript. Here is an example of a Typescript sort array by date.

let stringDates: string[] = ['2025-12-25', '2025-01-01', '2025-07-04'];let sortedDates = stringDates .map(date => new Date(date)) .sort((a, b) => a.getTime() - b.getTime()) .map(date => date.toISOString().substring(0, 10));console.log(sortedDates);

In this example, we:

  1. Map the array of string dates to an array of Date objects.
  2. Sort the array using the getTime() method.
  3. Convert the sorted Date objects back into strings for easier readability.

Output:

[ '2025-01-01', '2025-07-04', '2025-12-25' ]

Here, you can see the output in the screenshot below.

Typescript sort by date | Typescript sort array by date - SPGuides (2)

Sort an Array of Objects by Date Property in Typescript

Often, you’ll need to sort an array of objects based on a date property. Here is a complete code for the Typescript sort array by date property.

interface Event { name: string; date: Date; } let events: Event[] = [ { name: 'New Year', date: new Date('2025-01-01') }, { name: 'Independence Day', date: new Date('2025-07-04') }, { name: 'Christmas', date: new Date('2025-12-25') } ]; events.sort((a, b) => a.date.getTime() - b.date.getTime());

Here, we sort the events array based on the date property of each object.

Sorting and Formatting Dates for Display in Typescript

In many applications, you’ll need to sort dates and then format them for display. TypeScript can be used alongside libraries like date-fns or `moment.js’ for more complex date manipulations and formatting.

import { format } from 'date-fns';let dates: Date[] = [ new Date('2021-12-25'), new Date('2021-01-01'), new Date('2021-07-04')];dates.sort((a, b) => a.getTime() - b.getTime());let formattedDates = dates.map(date => format(date, 'MMMM d, yyyy'));

In this example, we first sort the dates and then format them using date-fns.

Typescript sort array by date – Another Example

Here, we will see how to sort arrays by date using the sort method in typescript.

See also Typescript convert string to keyof [4 examples]

For example, we have an array of objects, and based on the date we will sort the objects in ascending order in typescript. In the app.ts file write the below code:

const emp = [ {"id":10, "name":"John", "age":31, "gender":"m", "category":"G",date: new Date('2022-04-21')}, {"id":11, "name":"Alex", "age":35, "gender":"m", "category":"G",date: new Date('2022-08-23')}, {"id":12, "name":"Ammy", "age":20, "gender":"m", "category":"G",date: new Date('2022-06-14')}, {"id":13, "name":"Ron", "age":24, "gender":"W", "category":"M",date: new Date('2022-07-22')}];const sortedAsc = emp.sort( (objA, objB) => objA.date.getTime() - objB.date.getTime(), );console.log(sortedAsc);

To compile the code, run the below command and see the result in the console.

ts-node app.ts
Typescript sort by date | Typescript sort array by date - SPGuides (3)

This is an example of a Typescript sort array by date.

Typescript sort array of objects by date descending

Here, we will see how to sort of objects by date descending using sort() method in typescript.

For example, we have an array of objects, and based on the date, we will sort the objects in descending order in typescript. In the app.ts file, write the below code:

const emp = [ {"id":10, "name":"John", "age":31, "gender":"m", "category":"G",date: new Date('2022-04-21')}, {"id":11, "name":"Alex", "age":35, "gender":"m", "category":"G",date: new Date('2022-08-23')}, {"id":12, "name":"Ammy", "age":20, "gender":"m", "category":"G",date: new Date('2022-06-14')}, {"id":13, "name":"Ron", "age":24, "gender":"W", "category":"M",date: new Date('2022-07-22')}];//--descending order----const sortedDesc = emp.sort( (objA, objB) => objB.date.getTime() - objA.date.getTime(),);console.log(sortedDesc);

To compile the code, run the below command, you can see the result in the console.

ts-node app.ts
Typescript sort by date | Typescript sort array by date - SPGuides (4)

This is an example of a Typescript sort array of objects by date descending.

Conclusion

In this Typescript tutorial, I have explained everything about Typescript sort by date. Especially, I have explained how to sort array by date in Typescript. We saw various examples of Typescript array sort by date.

See also override Keyword in Typescript

You may also like:

  • Typescript reverse array
  • Typescript filter array of objects
  • Typescript sort array of objects by date descending
  • How to convert an array to a dictionary in Typescript?

Typescript sort by date | Typescript sort array by date - SPGuides (5)

Bijay Kumar

I am Bijay a Microsoft MVP (10 times – My MVP Profile) in SharePoint and have more than 17 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com

Typescript sort by date | Typescript sort array by date - SPGuides (2024)

FAQs

How to sort a date array in TypeScript? ›

How to Sort an Array in TypeScript ?
  1. Method 1: Using sort method.
  2. Method 2: Spread Operator.
  3. Method 3: Custom Sorting Function.
  4. Method 4: Using a Priority Queue for Custom Sort Order.
Jun 3, 2024

How to sort an array using TypeScript? ›

To sort an array in TypeScript we could use Array. sort() function. The Array. sort() is an inbuilt TypeScript function that is used to sort the elements of an array.

How do you sort an array of objects by date? ›

To sort an object array by date using `Intl. DateTimeFormat` and `Array. prototype. sort()`, convert the date strings to formatted dates, then use the `sort` method with a custom compare function that compares the formatted dates.

How to sort date string array in Java? ›

Additionally, to sort a list of date-time strings, we can take a three-step approach:
  1. Convert String elements to LocalDateTime instances.
  2. Sort those LocalDateTime objects.
  3. Convert the LocalDateTime objects back to Strings.
Jan 8, 2024

How do you sort by Date range? ›

Sort dates or times
  1. Select a cell in the column you want to sort.
  2. On the Data tab, in the Sort & Filter group, do one of the following: To sort from an earlier to a later date or time, click. (Sort Oldest to Newest). To sort from a later to an earlier date or time, click. (Sort Newest to Oldest).

How to search in array in TypeScript? ›

The find() method in TypeScript searches the first element in the array, that satisfies the conditions of the testing function. If no element in the array satisfies the condition, the method returns undefined.

How do you compare dates in TypeScript? ›

To check if one date is before another in TypeScript, you can use the less than operator (<) or the greater than operator (>) depending on the desired comparison. and log the result to the console.

How do I search sort by date? ›

Google: Google has a "Tools" button that appears below the search bar after you've entered your query. You can click on this button and select "Any Time" to sort results by date, such as past hour, past 24 hours, past week, or past month.

How do you sort an array in order? ›

The sort() method can be used to sort elements of an array in ascending order based on Unicode character code values by default.

What is ascending order by date? ›

For data with numbers and letters/words, such as address lines, the sort is most likely alphanumeric meaning 0-9 is sorted first then followed by A-Z. For dates, the sort will be oldest/earliest dates to most recent. The oldest dates will be at the top of the list.

How do you sort a string array? ›

Algorithm:
  1. Initialize the string with the input words.
  2. Calculate the string length.
  3. Sort the string array according to the length of words in ascending order With the help of insertion sort.
  4. Print the sorted array.
Mar 7, 2023

How to sort an ArrayList of dates in Java? ›

Inside the compare method for return value use the compareTo() method which will return the specified value by comparing the DateItem objects. Now in the main method use Collections. sort() method and pass the ArrayList and 'SortItem' class object to it, it will sort the dates, and output will be generated.

How to get Date in specific format in TypeScript? ›

Using toLocaleDateString() method

The toLocaleDateString method allows us to customize the date format by specifying options such as the year, month and day. We mostly use this approach when we want to control individual date components according to the desired format.

How to sort an array of dates in C? ›

How to sort an array of dates in C/C++? Given an array of dates, how to sort them. The idea is to use in-built function to sort function in C++. We can write our own compare function that first compares years, then months, then days.

How to format array of dates in JavaScript? ›

Use native groupBy function

const items = [ {"created_at": "2023-06-01", "value": 10}, {"created_at": "2023-06-02", "value": 20}, {"created_at": "2023-06-01", "value": 30}, {"created_at": "2023-06-03", "value": 40}, {"created_at": "2023-06-02", "value": 50}, ]; let groups = Object.

Top Articles
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 5568

Rating: 4.8 / 5 (58 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.