Sorting Javascript Objects in Ascending Order by Date

Image by Pexels from Pixabay

Scenario

Have have the following Typescript class instances:

class DateClass {
constructor(public name: string, public receiptDate: Date) {}
}
const d1 = new DateClass('d1', new Date(3));
const d2 = new DateClass('d2', new Date(2));
const arr: DateClass[] = [d1, d2];

And we wish to sort them in the following order:

[d2, d1]

Approach

const sorted = arr.sort((a, b) => {return a.receiptDate.getTime() - b.receiptDate.getTime();});console.log(sorted);

Demo

Founder of Firefly Semantics Corporation

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Master the JavaScript Interview: What’s the Difference Between Class & Prototypal Inheritance?

Code Splitting in React — All You Need to Know

The Best GPS Running Watches Reviewed & Tested https://t.co/iWXQr3iMd9 https://t.co/BblicnWljC

Customizable Content Slider with React Native and Reanimated 2, Part 1

Design Patterns — Singleton Pattern

Create a NEWS App using Next JS and React Query

Starting React

All you need to know about A/B testing Single Page Applications with Google Optimize

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ole Ersoy

Ole Ersoy

Founder of Firefly Semantics Corporation

More from Medium

JavaScript/TypeScript Array Filter

Formatting Javascript Strings and Numbers to 2 Decimal Places

It is Re-active angular , vue ,react bad or

React vs Angular — Which One’s Better for Your Frontend?