Arrange in TypeScript by various fields

I am facing an issue with sorting on multiple fields in my array

Here is the array:

details = [
{
  dateDebut: '2014-10-10',
  rank:1
},
{
  dateDebut: '2020-12-12',
  rank:0
},
{
  dateDebut: '2014-10-10',
  rank:0
},
{
  dateDebut: '2014-10-10',
  rank:2
},
{
  dateDebut: '2020-11-11',
  rank:1
},
{
  dateDebut: '2020-11-11',
  rank:0
}
]

I would like to sort by descending date and rank to achieve the following result:

 details = [
    {
      dateDebut: '2020-12-12',
      rank:0
    },
    {
      dateDebut: '2020-11-11',
      rank:1
    },
    {
      dateDebut: '2020-11-11',
      rank:0
    },
    {
      dateDebut: '2014-10-10',
      rank:2
    },
    {
      dateDebut: '2014-10-10',
      rank:1
    },
    ,
    {
      dateDebut: '2014-10-10',
      rank:0
    },
]

In my project, Luxon is used for handling dates. I have tried a certain treatment but haven't been successful. Can you please assist me?

This is how I am trying to implement it:

details.sort((d1, d2) => this.myService.sortByRangAndDates(d1, d2, 'desc'));

Here is the snippet from my service file:

sortByRankAndDates(d1: Details, d2: Details, order: 'asc' | 'desc'): number {
    const orderValue = order === 'desc' ? -1 : 1;

    const convert = (s: string): number => {
      return s ? new Date(s).getUTCDate() : 0;
    };


    return (convert(d1?.dateDebut) < convert(d2?.dateDebut)) || (d1.rank < d2.rank ) ? orderValue :
      (convert(d1?.dateDebut) > convert(d2?.dateDebut)) || (d1.rank > d2.rank ) ? -1 * orderValue : 0;

  }

Your help would be greatly appreciated. Thank you!

Answer №1

Enhanced the code and implemented two sorting functions. The first function sorts by date, and if the dates are the same, it then sorts by rank.

type Details = {
  dateDebut: string;
  rank: number;
};
const convert = (s: string): number => s ? new Date(s).getTime() : 0

const sortByDate = (d1: Details, d2: Details, order: string): number =>
  order == "asc"
    ? convert(d1.dateDebut) > convert(d2.dateDebut)
      ? 1
      : -1
    : convert(d1.dateDebut) > convert(d2.dateDebut)
    ? -1
    : 1;

const sortByRank = (d1: Details, d2: Details, order: "asc" | "desc"): number =>
  d1.dateDebut == d2.dateDebut
    ? order == "asc"
      ? d1.rank > d2.rank
        ? 1
        : -1
      : d1.rank > d2.rank
      ? -1
      : 1
    : 0;
details.sort((d1, d2) => sortByDate(d1, d2, "desc"));
details.sort((d1, d2) => sortByRank(d1, d2, "desc"));

console.log(details);

Check out the TypeScript playground link here: https://tsplay.dev/WzLKQN

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble with my React component timer not functioning properly

How can I utilize the Header Component as a Clock timer for my webpage to update every second? Despite searching on Google, I couldn't find examples that match my requirements. Why is the tick() function not functioning properly even though there are ...

Transitioning to TypeScript has brought the promise of imports returning once again

I've been facing some challenges while migrating my extensive project to TypeScript, particularly with handling imports. Being relatively new to programming, I'm unsure if my previous approach was considered bad practice. Previously, I organized ...

Discovering the type in Typescript without explicitly defining a type variable for the callback

I am looking for a solution to wrap rxjs subscribe's next callback with my own function: type Handler<T> = (value: T) => void; export function withTryCatch<T>(callback?: Handler<T>): Handler<T> { return (value: T) => ...

Using TypeScript with React Bootstrap's <Col> component and setting the align attribute to 'center' can trigger a TS2322 warning

The React app I'm working on includes the code below. The Col component is imported from React-bootstrap <Col md={5} align="center"> This is a column </Col> When using Typescript, I received the following warning: ...

What is the best way to display data retrieved through an HTTP service using ngFor?

I was attempting to inject a service (contact.service.ts) into a component (contact-list.component). The service contains data on employees defined in contacts.ts. While I was able to successfully receive the data, I encountered difficulty in rendering it ...

What is the process of encapsulating a callback function within another callback function and invoking it from there?

Here is the code snippet I am working with: var me = this; gapi.auth.authorize({ client_id: client, scope: scope, immediate: true }, function (authResult: any) { if (authResult && !authResult.error) { me ...

When RouteProps is used to initialize useState, the state is not set

I am facing a dilemma with a component that utilizes useState. The state is initially set using a property from RouteComponentProps. Strangely, it functions correctly when I manually type the URL in the browser's address bar, but not when the URL is c ...

Utilizing unauthorized fetch methods to modify the urql Client's fetch function contradicts TypeScript requirements

I've been struggling to make Typescript happy while redefining the fetch function on @urql/core. Although I came across two helpful solutions on Stack Overflow that seemed to address the issue, unfortunately they didn't quite work for me: fetch ...

Service consuming in Angular 2 using Stomp protocol

Why am I seeing responseBody as undefined, but I am able to see the subscribe response in msg_body? What could be causing this issue with responseBody? let stomp_subscription = this._stompService.subscribe('/topic/queue'); stomp_subscription.ma ...

The variable in my NodeJS code is persisting across multiple requests and not being reset as expected

After setting up a project with the help of Typescript-Node-Starter, I have successfully created a controller and a route to call a specific function. import { Request, Response } from "express"; import axios from "axios"; import { pars ...

Can a function's return type be set to match the return type of its callback function?

Check out the following function export const tryAsyncAwait = async (fn: () => any) => { try { const data = await fn(); return [data, null]; } catch (error) { return [null, error]; } }; If I use this function as an example... const ...

Display a single unique value in the dropdown menu when there are duplicate options

Hey there, I'm currently working on retrieving printer information based on their location. If I have multiple printers at the same location, I would like to only display that location once in the dropdown menu. I am aware that this can be resolved at ...

Efficient Typescript ambient modules using shorthand notation

Exploring the code snippet from the official module guide, we see: import x, {y} from "hot-new-module"; x(y); This syntax raises a question: why is 'x' not within curly brackets? What does this coding structure signify? ...

React with Typescript allows us to refine the callback type depending on the presence of an optional boolean prop

In my project, there's a component <Selector /> that can optionally accept a parameter called isMulti: boolean. It also requires another parameter called onSelected, whose signature needs to change depending on the value of isMulti (whether it i ...

Angular 5 - Jasmine Tests explained: Encounter with the puzzling error message: "Error: Provider for the NgModule 'DynamicTestModule' is invalid, as only instances of Provider and Type are permitted"

I'm having trouble running tests on a component class. Here's the error message from the stack: Error: Invalid provider for the NgModule 'DynamicTestModule' - only instances of Provider and Type are allowed, got: [AlertModaldataCompon ...

Seeking out a particular key within a JSON object and then finding a match based on the id within that key's array - how can it be

Recently, I've been exploring JavaScript and encountering challenges when trying to apply array methods on objects. For instance, I received a fetch response and my goal is to extract the 'entries' key and then utilize the native Array.find( ...

What could be causing the data-* prefix to malfunction in Angular 9?

I'm facing an issue with a basic component in Angular 9. Check out the code below: Component : @Component({ selector: 'hello', template: `<h1>Hello {{name}}!</h1>`, styles: [`h1 { font-family: Lato; }`] }) export class He ...

Searching for a streamlined approach to retrieve a segment of a string

I'm currently working with JavaScript and TypeScript. Within my code, I encountered a scenario where I have a string that might contain certain tags indicating importance or urgency. Here are a couple of examples: A: "Remind me to go to the store to ...

Is it possible for a primitive value to function as a type within Typescript?

Is it possible for a primitive value to be considered as a type in Typescript? For example, is the type below considered valid? If not, how can it be modified to make it valid? export type Status = { completed: false; } ...

Troubleshooting a NextJs/TS problem with importing ESM modules

Click here for the Code Sandbox I'm currently in the process of transitioning some code to NextJS 11 / Webpack 5, including certain modules that now exclusively support ECMAScript Modules (esm). Prior to the upgrade, I could easily export all files ...