What is the best way to order this Graphql array using my Typescript resolver?

My goal is to arrange my array of objects in descending order based on 'price' when the sortPrice parameter is set to true.

To achieve this, I am utilizing the 'type-graphql' library for my resolver and the 'fast-sort' package for sorting the data in descending order.

Below is a snippet of my resolver code - please note that the price filter is functioning correctly.

  // Price filter
  if (minPrice) {
    filteredItems = filteredItems.filter((item: any) => item.price >= minPrice);
  }

  if (maxPrice) {
    filteredItems = filteredItems.filter((item: any) => item.price <= maxPrice);
  }

  // Sort price/rating

  if (sortPrice) {
    filteredItems = filteredItems.filter((item: any) => sort(items).desc());
  }

Additionally, here is a preview of my GraphQL playground query - it's evident that the array is not sorted by price as expected.

https://i.sstatic.net/16A7A.png

Answer №1

My current use case involves utilizing the following code snippet to effectively sort an array of objects based on specific criteria. This function allows for sorting in either ascending or descending order, and supports sorting by one or multiple keys. I initially came across this solution on stackoverflow a few weeks ago and made some modifications to tailor it to my needs. Additionally, I have implemented an enum to enhance the safety of the code. While the implementation provided is in typescript, it can easily be converted to Javascript after removing the type annotations and interfaces.

export declare enum EOrderBy {
    ASC = "ASC",
    DESC = "DESC"
}

export interface ISortConfig<T> {
    column: keyof T;
    order?: keyof typeof EOrderBy;
    map?: itemMap;
}

export const sortByValues = <T extends object>(
    columns: (keyof T | ISortConfig<T>)[]
): ((a: T, b: T) => 0 | 1 | -1) => {
    return function (a: T, b: T) {
        // Implementation logic
    };
};

export const sortArray = <T extends object>(
    array: T[],
    columns: (keyof T | ISortConfig<T>)[]
) => {
    return array.sort(sortByValues<T>(columns));
};

An example illustrating the usage:

interface IObj {
    name: string;
    prenom: string;
    montant: number;
}

const arrobj: IObj[] = [
    {
        name: "al",
        prenom: "jero",
        montant: 10,
    },
    {
        name: "al",
        prenom: "ale",
        montant: 100,
    },
    {
        name: "zozo",
        prenom: "aa",
        montant: 10,
    },
];

// Simple ordering example
console.log(sortArray(arrobj, [{ column: "prenom", order: "ASC" }]));
console.log(sortArray(arrobj, [{ column: "montant", order: "DESC" }]));


// Ordering by several properties (montant DESC followed by name ASC)
console.log(
    sortArray(arrobj, [
        { column: "montant", order: "DESC" },
        { column: "name", order: "ASC" },
    ])
);

// Preparing the orderBy parameter in a variable before passing it to the function
const orderBy: IOrderBy<IObj>[] = [
    { column: "name", order: EOrderBy.DESC },
    { column: "prenom", order: EOrderBy.DESC },
];

console.log(sortArray(arrobj, orderBy));

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

Nested Angular formArrays within formArrays

Currently working on inline editing in my project, I am attempting to patch value data from the server. Within my formArray for the accountNumbers array, I am encountering an issue when trying to change the value of inputs. The error message reads: Error: ...

Find the minimum and maximum sum of five integers with Min-Max Sum challenge

Given a set of five positive integers, calculate the minimum and maximum values that can be obtained by summing exactly four of the five integers. Print the resulting minimum and maximum values on a single line, separated by a space. Example: arr = [1, 3 ...

Retrieve Information in a List

I am currently facing an issue while trying to retrieve data from an array. Below is an example of the image array that I am working with. I am specifically looking to get the weather icon data, but unfortunately I encountered this error message: core.js:1 ...

Cannot display data in template

After successfully retrieving JSON data, I am facing trouble displaying the value in my template. It seems that something went wrong with the way I am trying to output it compared to others. My function looks like this, getUserInfo() { var service ...

What is the most effective way to iterate through an array of objects and retrieve the results in a key-value format?

I am dealing with an array of objects that may seem a bit complex initially, but I will simplify it as much as possible. Each object in the array has properties like Engineering, Environment, and others, each containing a sub-object called radars. The rada ...

JavaScript and Memory Allocation: Working with Array Elements

If I may ask a brief question driven by curiosity: imagine having an object with an array as a property, like this.arr = ["one", "two", "three", ...], and let's say this array is filled with n elements. What will occur to these elements if we execute ...

The JSX component cannot be named 'Stack.Navigator' or used as such

Encountering a type issue with react navigation using Stack.Navigation or Stack.Group from createNativeStackNavigator The error message indicates that the types do not match with JSX.element. Specifically, it states: Type '{}' is not assignable ...

The value assigned to a dynamically created array in a void function may not be the same when returned in the main() function

Having a bit of trouble with dynamic arrays in my C program. Everything was running smoothly until I was required to move the creation of the dynamic array into a separate void function. After doing so, the program continued to work fine until I needed to ...

Verify whether there are any values in the array that are not equal to 0000-00-00

I'm trying to determine if there are any values in the array below that are not "0000-00-00" $periods = array("0000-00-00", "0000-00-00", "0000-00-00", "0000-00-00"); My expected output: $periods = array("0000-00-00", "0000-00-00", "0000-00-00", "2 ...

Tips for creating a versatile object combine function in TypeScript

Is there a way to create a generic function in TypeScript 4.4+ that is equivalent to {...a,...b} operation? Both a and b are records, but their types are unknown in advance. I want to define a generic type that enforces arbitrary functions to perform the { ...

Creating an object with a property in typescript

Recently, I made the switch from JavaScript to TypeScript and now I am in the process of converting a lot of my code. I used to frequently use this snippet in JavaScript (which has been converted to TypeScript): function isObject (payload: any): payload ...

Move on to a different screen in a React Component once the data has been fetched

Currently, I am delving into the world of React and TypeScript and attempting to utilize "react-router-dom" in order to create a login component that will interact with my backend server. Essentially, my goal is to develop a "Login" class that, upon form ...

Uncovering the Magic of TypeScript Type Inference with Generics and Function Objects

As I attempted to create a versatile function that can accept an interface containing both functions and data, there seems to be an issue with inference. Assistance in resolving this problem would be greatly appreciated. To view the code that is failing t ...

When attempting to execute node, execSync encounters an error

Within an EC2 instance, I am executing a series of processes. To initiate it, I use an SSM command: cd / && cd home/ec2-user && . .nvm/nvm.sh && cd ufo && npm run start Inside this process, there is a method in app.ts that ...

Ways to modify a number in grafbase

When attempting to update an integer in grafbase, I encounter the error "Expected an Object for". The issue arises during the update process even though everything appears to be correctly set up. Here is the mutation code: export const updatePetMutation = ...

What is the best method for altering a route in React while utilizing Typescript?

I recently started coding along with the ZTM course and am working on a face recognition app. Instead of using JavaScript, I decided to use TypeScript for this project in order to avoid using the any type. However, as a beginner in this language, I'm ...

Strict mode in IE11 does not allow multiple definitions of a property in Angular 2+

After adding pollyfills, I encountered an error in Internet Explorer 11 within my main.bundle.js file on line 9692. Despite examining the compiled code, I am unable to decipher its meaning. The snippet of code causing the issue is as follows: styles: ...

Navigating Perl: Unraveling the Mysteries of Accessing Hashes Within an

I have a unique Hash structure that I think refers to an array of hashes. I'm trying to figure out how to access the individual hash elements within this array. UPDATE: Here is the detailed hash structure $VAR1 = { 'CVE-2015-0677' =& ...

A step-by-step guide to activating multi-selection in the Primary SideBar of Visual Studio Code using your custom extension

Currently, I'm in the process of developing an extension for Visual Studio Code where I've added a new activityBar containing treeViews that showcase information pulled from a JSON file. My goal is to enable users to multi-select certain displaye ...

The module "angular2-multiselect-dropdown" is experiencing a metadata version mismatch error

Recently, I updated the node module angular2-multiselect-dropdown from version v3.2.1 to v4.0.0. However, when running the angular build command, I encountered an "ERROR in Metadata version mismatch for module". Just to provide some context, I am using yar ...