arranging a list in which the second characteristic might not be present

Looking for a solution to sort a table in an Angular project? The challenge is sorting by either a direct property of objects in the array or a child of that property. Take, for instance, sorting by associate.lastname versus associate.client.name. I've managed to accomplish this within a single TypeScript method.

Here's the code snippet for the sortBy method within my component's class:

sortBy(option: SortOption, sortedBy: string) {
    const props = option.split('.');
    const parent = props[0];
    const child = props[1];
    const asc = this[sortedBy];
    if (!child) {
        // Sorting logic for when only parent property is involved
    } else {
        // Sorting logic for when both parent and child properties are involved
      }
      this[sortedBy] = !this[sortedBy]
}

This method effectively handles different scenarios depending on whether there is a child property to be considered. However, I'm curious to know if there's a more concise way to achieve the same results. Despite the similarity between the if and else statements, I can't seem to find a cleaner approach.

Do you have any suggestions for improving this method?

Answer №1

To improve efficiency, consider creating a sorting key function:

let customSortingKey: (item: any) => number;  
if (category) {
    customSortingKey = (item) => item[parent][category];
} else {
    customSortingKey = (item) => item[parent];
}

Once the sorting key function is defined, you can simplify the sorting process:

this.items.sort((itemA, itemB)=> {
    if (customSortingKey(itemA) < customSortingKey(itemB)) {
        return order === true ? -1 : 1;
    } else if (customSortingKey(itemB) < customSortingKey(itemA)) {
        return order === true ? 1 : -1;
    } else {
        return 0;
    }
});

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

Obtaining a Comprehensive Response (not limited to just the body) through Angular 4 HTTP Requests

I am currently working on getting a full response from my HTTP calls. Following the guidelines in the Angular documentation, I have set my HTTP call options as {observe: 'response'} However, when I implement this, I encounter the following error ...

How can you explain an array that holds an object (stdClass) along with @phpstan-return in PHP DocBlock? - PHPStan

I have a PHP function example (8.2) that returns an array. Within this array, there is an additional object, specifically a stdClass. I utilize PHPStan as a static analysis tool. How can I correctly specify the structure of this object in terms of syntax ...

Specifying the data type of the input being passed into a .css() function within a jQuery ID selector

Currently, I am facing an issue where I need to position an element below a fixed toolbar. The amount of top-padding required for this positioning varies based on the viewport width. To address this, I have created a formula that calculates the percentage ...

I want to know how to keep additional inline whitespace while using the default JS/TS formatter in VS Code

Take this line, for example: var x = 5; var yyyyy = 10; var zzzzzz = 15; The VS Code Formatter removes the extra spaces between variable names and values. var x = 5; var yyyyy = 10; var zzzzzz = 15; Is there a way to configure it to keep the f ...

PHP - Determine the number of elements in an array by comparing it to another

I have an array structured like this: $array1 = array(Array('b','d'), Array('c','a'), Array('b','d'), Array('a','d'), ...

Guide on building a basic cache system with RxJs

I am interested in developing a caching service using RxJs. The concept is quite simple - I have a class that retrieves initial data from a server and a websocket that sends notifications to this service regarding additions, edits, or deletions of entities ...

What is the best way to integrate OAuth into a stateless REST API?

Is there a way to utilize OAuth statelessly on a node/express server without breaking the statelessness of my REST api while using Passport for transferring user information through sessions? ...

Let's compare the usage of JavaScript's toUTCString() method with the concept of UTC date

When I fetch the expiry date time in UTC from the Authentication API along with a token, I use the npm jwt-decode package to extract the information. private setToken(value: string) { this._token = value; var decoded = jwt_decode(value); this._ ...

The style from '<URL>' was not applied as it has a MIME type of 'text/html', which is not a compatible stylesheet MIME type

After attempting to run the angular application with the home component, an error appeared stating that styles were refused and images could not be found. It's puzzling because the CSS and image folder are located in the /src/assets folder. I have tr ...

Troubleshooting Nested Arrays in JavaScript

I have been receiving API JSON data in a specific format and am currently working on reorganizing it. The goal is to group the data first by the start_date and then by the phys_id. The aim is to showcase the available appointment dates followed by each pro ...

Achieve triple condition handling using *ngIf else technique

My goal is to suggest nearby establishments to the user based on their location. I need to handle two scenarios: The user has allowed access to their geolocation The user has not granted access to their geolocation While checking if the geolocation ser ...

"Incorporating Arrays into CMFCPropertyGridProperty for enhancing dropdown list functionality within MFC MDI application and consolidating MP

I am seeking advice on how to implement a dropdown list populated from an array of data after parsing information from the MP4 Tag. The current functionality works perfectly fine, and this is just an additional feature I want to include. Specifically, I am ...

Encountering issue when attempting to reset stepper component in angular

In my current project, I am implementing an angular stepper with two screens. If a user navigates back to step 1 by clicking the back button or directly on a label, I want to reset the stepper using the reset() function. However, when I attempt to navigate ...

Exploring the differences between filtering a collection in Backbone.js and an array in Underscore.js

I'm currently attempting to achieve a similar result to the question linked below, but with an array and the goal of returning all objects using the values of the corresponding array rather than just the value itself: Filtering backbone collection by ...

Typescript ensures that the return type of a function is a key of an interface, which is determined based

I am attempting to enforce a specific return type from a function based on the key passed to it. For example, if the key is service1, then the correct return type should be Payloads['service1']. How can I accomplish this? interface Payloads { ...

[Angular 10][Rxjs] How come the second pipe is not activating?

I am facing an issue where I have two subscribers to the same Observable, but the second one is not emitting any values. Could there be a limitation within the pipe that I am unaware of? component.ts private readonly destroyed$ = new Subject<void> ...

Pause and anticipate the subscription within the corresponding function

Is there a way to make an If-Else branch wait for all REST calls to finish, even if the Else side has no REST calls? Let's take a look at this scenario: createNewList(oldList: any[]) { const newList = []; oldList.forEach(element => { if (eleme ...

Tips for retrieving additional values from a chosen variable in Angular 10

Here is an array I have: export const Glcode = [ { id: 1, Type: 'Asset', Name: 'Cash at Head Office', code: '10018' }, { id: 2, Type: 'Asset', Name: 'POS ACCOUNT ', code: '10432' }, { ...

"Can you guide me on how to deactivate the template tab feature in compodoc

I was in need of a documentation generator tool for my Angular 2 application and came across compodoc which proved to be quite helpful for me. When using this tool, I noticed that in the component section, I did not want to include the source code and tem ...

Splitting Angular Components with Angular as-split

Having trouble adding a "title" to my angular as-split-area. The titles are appearing together rather than above the as-split-area. <div style="width: 800px; height: 400px; background: yellow;"> <as-split direction="vertical&q ...