What is the best way to organize a collection of objects by a specific characteristic in Typescript?

Imagine you have an array of objects with the following structure:

type Obj = {
  id: number,
  created: Date, 
  title: string
}

How can you effectively sort this array based on a specific property without encountering any issues in the type system? For instance:

const numberSorted = objArray.sortBy("id");
const dateSorted = objArray.sortBy("created");
const stringSorted = objArray.sortBy("title");

Answer №2

To create a custom sorting function, you can use the following structure:

function sortByCustom<T, V>(
        array: T[],
        valueExtractor: (t: T) => V,
        comparator?: (a: V, b: V) => number) {

  // Note that this default comparison logic is basic and may need adjustment
  const c = comparator ?? ((a, b) => a > b ? 1 : -1) 
  return array.sort((a, b) => c(valueExtractor(a), valueExtractor(b)))
}

You can then utilize it like this:

interface Type { a: string, b: number, c: Date }
const arr: Type[] = [
  { a: '1', b: 1, c: new Date(3) },
  { a: '3', b: 2, c: new Date(2) },
  { a: '2', b: 3, c: new Date(1) },
]
const sortedA: Type[] = sortByCustom(arr, t => t.a)
const sortedC: Type[] = sortByCustom(arr, t => t.c)
// If you require a different comparison method
const sortedX = sortByCustom(arr, t => t.c, (a, b) => a.getDay() - b.getDay())

This function also supports nested properties within objects like t => t.a.b.c or other scenarios where additional transformation of sort keys is needed, such as t => t.a.toLowerCase()

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

Receive regular updates every week for an entire month using Javascript

How can I calculate the number of check-ins per week in a month using Javascript? I have been unable to find relevant code for this task. Specifically, I am interested in determining the total count of user check-ins on a weekly basis. For example, if a u ...

What is the process for calculating a class property in typescript?

If I were writing this in JavaScript, it would look like: function a(b,c) {this.foo = b; this.bar = c; this.yep = b+c} // undefined b = new a(1,2) // a {foo: 1, bar: 2, yep: 3} However, I've been struggling to achieve the same in TypeScript. None of ...

Angular 8: Issue with PatchValue in Conjunction with ChangeDetector and UpdateValue

I am puzzled by the fact that PatchValue does not seem to work properly with FormBuilder. While it shows data when retrieving the value, it fails to set it in the FormBuilder. Does anyone have an idea why this might be happening? I am utilizing UpdateValue ...

Is it possible to pass a number instead of a string to Angular's matToolTip within a mat-icon-button? If not, is there a way to convert the number to a string within an Angular

In my current situation, I am facing a challenge with the following line of code: [matTooltip]="ratingId + 1". This line is crucial as it forms part of the arguments for a Material Design button. However, in this case, things are not straightfo ...

Have you noticed the issue with Angular's logical OR when using it in the option attribute? It seems that when [(ngModel)] is applied within a select element, the [selected] attribute is unable to change

Within the select element, I have an option set up like this: <option [selected]=" impulse === 10 || isTraining " value="10">10</option> My assumption was that when any value is assigned to impulse and isTraining is set to true, the current o ...

The exploration of child routes and modules

I'm currently working on a somewhat large project and I've decided to break it down into modules. However, I'm facing an issue with accessing the routes of admin.module.ts. In my app.module, I have imported the admin Module. imports: [ Br ...

Creating a Modal using Typescript with NextJS

Currently, I'm working on creating a modal within my app using NextJS with Typescript. Unfortunately, I've been struggling to eliminate the warning associated with my modal selector. Can someone provide guidance on how to properly type this? cons ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

I can't figure out why I'm getting the error message "Uncaught ReferenceError: process is not defined

I have a react/typescript app and prior to updating vite, my code checked whether the environment was development or production with the following logic: function getEnvironment(): "production" | "development" { if (process.env.NODE_E ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

How should I structure my MySQL tables for efficiently storing a user's preferences in a map format?

My current project involves developing a web application that provides administrators with the ability to manage user information and access within the system. While most user details like name, email, and workID are straightforward, I am facing difficulty ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

Leverage the power of ssh2-promise in NodeJS to run Linux commands on a remote server

When attempting to run the command yum install <package_name> on a remote Linux server using the ssh2-promise package, I encountered an issue where I couldn't retrieve the response from the command for further processing and validation. I' ...

Can we access global variables directly in an Angular 2 HTML template?

After setting the app.settings as shown below public static get DateFormat(): string { return 'MM/DD/YYYY';} I need to utilize it in one of my HTML templates for a component. This is what I want to achieve. <input [(ngModel)]="Holiday" [dat ...

What are the benefits of using one state in React with useState compared to having multiple states?

Is it more beneficial to optimize and enhance code readability in React using Hooks and Functional components by utilizing a single setState hook or having multiple hooks per component? To further elaborate, let's consider the following: When workin ...

Using the original type's keys to index a mapped type

I am currently developing a function that is responsible for parsing a CSV file and returning an array of objects with specified types. Here is a snippet of the code: type KeyToTransformerLookup<T> = { [K in keyof T as T[K] extends string ? never : ...

Could anyone provide an explanation for the statement "What does '[P in keyof O]: O[P];' signify?"

As a new Typescript user looking to build a passport strategy, I came across a line of code that has me completely baffled. The snippet is as follows: here. The type StrategyCreated<T, O = T & StrategyCreatedStatic> = { [P in keyof O]: O[P]; ...

The parameter type `SetStateAction<EventDetails[] | undefined>` does not allow for assigning arguments

I am currently facing an issue in a ReactJS project where I am trying to update state that was initially set up like this: const [eventsData, setEventsData] = useState<EventDetails[]>(); Every time I try to update the state using setEventsData(obj), ...

What steps are involved in generating a Typescript module definition for a directory containing a babel-plugin-content-transformer?

Currently utilizing the babel-plugin-content-transformer to import a directory containing YAML documents in a React Native/Expo project. The configuration for my babel plugin looks like this: ['content-transformer', { transformers: [{ ...

Creating a new TypeScript file via the command line: A step-by-step guide!

When I want to create a new file named main.ts, I try to write the command but it keeps showing an error. "bash: code: command not found" https://i.stack.imgur.com/cpDy3.png ...