Slate - developing a TypeScript function to filter and retrieve an object containing the highest property value

Check out this NEW RELATED QUESTION:

I need to extract the largest number from a given object set.

I am struggling with finding a solution. I have tried using max but I think my skills are lacking. Here is the code I have so far:

     @Function()
    public async largestNumber(): Promise<Long> {
        const objResult = Objects.search()
                .dataMain()
                .filter(data_column => data_column.lngPlanningNumber.range. )
                .gt(100)
                .take(1);
                
        return objResult.max();
    }

This function currently retrieves objects with NULL values for the lngPlanningNumber property, which I want to exclude.

UPDATE:

Property 'isNotNull' does not exist on type 'INumericPropertyFilter'.

for

.filter(data_column => data_column.lngPlanningNumber.isNotNull()) // filter out NULL values 

Property 'take' does not exist on type 'Promise<number | null>'.

for

.take(1);

NEW RELATED QUESTION: my code

    @Function()
    @Edits(XYZ)
    public async fctLargestNumber(): Promise<XYZ[]> {
        const maxObject = Objects.search()
                .xYZ()
                // .groupBy(e => e.lngPlanningNumber.topValues())
                // .segmentBy(e => e.lngPlanningNumber.topValues())
                // .filter(data_column => data_column.lngPlanningNumber.byIRanges({ min: 100000, max: 999999 }))
                .orderBy(data_column => data_column.lngPlanningNumber.desc())
                .takeAsync(1)
                //.valueOf();         
        return maxObject;

now I am getting an output like this:

[
{"typeId":"my-collection","primaryKey":{"id_pk":"ee1b1ac1-008b-479b-a748-01e8702927c9"}}
]

The challenge now is how to retrieve my desired result.

  • How can I extract the primary key value?
  • How do I locate the requested integer value of column "lngPlanningNumber" associated with this id?

The Promise aspect intrigues me. Thank you

Answer №1

Yes, it is true that for numeric properties, you will only have access to the filters exactMatch and range. When using these filters, null values should be automatically removed.

If you want to include all values in a range, you can try setting the range from -99999 to 99999 as shown below:

const flight: ExampleDataFlight[] = Objects.search().exampleDataFlight()
            .filter(row => row.taxiOut.range().gte(-99999).lte(99999))
            .all();

As for the take(1) property, it requires ordering to function properly. In the example below, I used airtime to force the use of orderBy, but you can replace it with any property if you only need to use take(1).

const flight: ExampleDataFlight[] = Objects.search().exampleDataFlight()
            .filter(row => row.taxiOut.range().gte(-99999).lte(99999))
            .orderBy(row => row.airTime.asc())
            .take(1);

Answer №2

To accomplish this task, you can filter the object set, then order it in descending order based on the desired column, and finally use take(1) or takeAsync(1).

@Function()
public async findLargestObject(): Promise<DataMain[]> {
    return Objects.search()
            .dataMain()
            .filter(data => data.lngPlanningNumber !== null)
            ..orderBy(data => data.lngPlanningNumber.desc())
            .takeAsync(1);
}

Answer №3

@Function()
async function findLargestNumber(): Promise<DataMain[]> {
    const largestObject = Objects.search()
            .dataMain()
            .orderBy(data_column => data_column.lngPlanningNumber.desc())
            .takeAsync(1);         
    return largestObject;
}

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

Tips for managing numerous nested subscriptions

Looking to extract the id parameter from the route, fetch the corresponding task, and then its parent if applicable. Angular CLI: 7.1.4 Node: 11.6.0 OS: linux x64 Angular: 7.1.4 @angular-devkit/architect 0.11.4 @angula ...

Preserve Inference in Typescript Generics When Typing Objects

When utilizing a generic type with default arguments, an issue arises where the inference benefit is lost if the variable is declared with the generic type. Consider the following types: type Attributes = Record<string, any>; type Model<TAttribu ...

How can you update ngModel in Angular and mark the form as dirty or invalid programmatically?

My form is connected to a model as shown below In the component file: myTextModel: string; updateMyTextModel(): void { this.myTextModel = "updated model value"; //todo- set form dirty (or invalid or touched) here } Html template: <form #test ...

How do I insert items into an ES6 Map using a specific object key/value type in Typescript?

I'm looking to utilize Maps instead of object maps to define keys and values. However, it appears that Typescript doesn't fully support index types for ES6 Maps. Are there any alternatives or workarounds available? Furthermore, I want to enforce ...

parsing a TypeScript query

Is there a simpler way to convert a query string into an object while preserving the respective data types? Let me provide some context: I utilize a table from an external service that generates filters as I add them. The challenge arises when I need to en ...

Encountering the error message "Error: 'preserveValueImports' is an unknown compiler option" while setting up a SvelteKit project

https://i.stack.imgur.com/fnidk.png Every time I set up a new sveltekit project using TypeScript, I keep encountering the error "Unknown compiler option 'preserveValueImports'.ts" in the tsconfig.json file. The error shows up above the line wher ...

Developing personalized middleware definition in TypeScript for Express

I have been struggling to define custom middleware for our application. I am using [email protected] and [email protected]. Most examples of typing middleware do not involve adding anything to the req or res arguments, but in our case, we need to modify ...

transformation of categorized unions in software development

Experimenting with routing-controllers and its built-in class-transformer feature, I tried creating an interface for executing a search query based on either a location id or location coordinate. My aim was to utilize a discriminated union as a body parame ...

Exploring the Relationship Between Redux and ImmutableJS in Managing Nested State and Understanding the Computational Complexity of Immutable

Trying to grasp the concept of Immutability for my debut Redux (NGRX/Store) endeavor has been quite the challenge. Avoiding state mutation has been a struggle, especially while dealing with Object.assign({}) and state mutation errors. Thankfully, I stumble ...

Exploring the differences in object shapes using TypeScript

I'm currently working on defining an object that has the ability to hold either data or an error. export type ResultContainer = { data: any; } | { error: any; }; function exampleFunction():ResultContainer { return { data: 3 } } ...

Converting JSON to string in Typescript is causing an error where type string cannot be assigned to type '{ .. }'

Here's the code snippet I'm working with: interface ISource extends IdModel { source_type_id: number; network_id: number; company_connection_id: number; feed_id: number; connection_id: number; feed_ids: number[]; name: string; tag ...

React: Content has not been refreshed

MarketEvent.tsx module is a centralized controller: import * as React from 'react'; import EventList from './EventList'; import FullReduce from './FullReduce'; import './MarketEvent.less' export default class Mark ...

The viewport width in NextJS does not extend across the entire screen on mobile devices

I'm currently tackling a challenge with my NextJS Website project. It's the first time this issue has arisen for me. Typically, I set the body width to 100% or 100vw and everything works smoothly. However, upon switching to a mobile device, I not ...

What steps should be taken in order to resolve the error message "Type is missing an index signature"?

Is there a solution to this type error? The argument of type 'Query' is causing an issue as it cannot be assigned to the parameter of type 'Input'. This is due to the absence of an index signature in type 'Query'.(2345) In ...

Guide on importing an ES6 package into an Express Typescript Project that is being utilized by a Vite React package

My goal is to efficiently share zod models and JS functions between the backend (Express & TS) and frontend (Vite React) using a shared library stored on a gcloud npm repository. Although the shared library works flawlessly on the frontend, I continue to e ...

What could be causing the error message "why can't shows read property

Within my Ionic-Angular application, I have successfully loaded the content from the database and printed it on the console. However, I am facing an issue where I cannot bind this content to the view. The error message that appears is displayed in https:// ...

The useState variable's set method fails to properly update the state variable

I am currently developing an application with a chat feature. Whenever a new chat comes in from a user, the store updates an array containing all the chats. This array is then passed down to a child component as a prop. The child component runs a useEffect ...

Utilizing TypeScript 3.1: Easier Array Indexing with Enums in Strict Mode

Enabling TypeScript "strict" mode with "noImplicitAny" causes this code to fail compilation. I am looking for guidance on how to properly declare and use Arrays indexed by Enum values. namespace CommandLineParser { enum States { sNoWhere, sSwitchValu ...

A guide to efficiently removing an element in Angular using TypeScript by considering certain properties

I need help removing an element from an array based on any property such as its key, name, or email. HTML <tr *ngFor="let person of persons;" (click)="remove(person.key)"> <td>{{person.key}}</td> <td>{{person.name}}</td> ...

The change handler of the TS RadioGroup component, instead of returning an array of possible strings, returns a unique

My interface declaration for StopData is shown below: export interface StopData { stopName: string, stopType: 'stop' | 'waypoint' } I have implemented a radio group to choose the 'stopType', which consists of two radi ...