Is there a way to sort ngFor output according to a different array?

My data consists of outputs from 2 different shifts: one from 8pm to 8am and the other from 20am to 7am. I have used ngx-pipes to filter the output, but now I need to sort the Night Shift hours from 8pm to 7am in the morning.

I have an array that specifies the correct order of the hours.

shiftSelection = [
{
name: "Day Shift",
hours: [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
},
{
name: "Night Shift",
hours: [20, 21, 22, 23, 0, 1, 2, 3, 4, 5, 6, 7]
}]

data = [
{
"lineId": 1,
"hour": 0,
"input": 9136,
"output": 8850
}, 
... 
{
"lineId": 1,
"hour": 23,
"input": 9136,
"output": 8850,
}]

How can I arrange ngFor output based on another array?

<div *ngFor="let row of data | filterBy: ['hour']: currShift.hours :1 | groupBy: 'lineId' | pairs">
<span class="group-title">Line {{row[0]}}</span>
<ng-container *ngFor="let cell of row[1]"> 
<span class="cell" matTooltip="{{cell | json}}">{{cell.output}} 
</span>
</ng-container>
</div>

Something like this would be perfect:

*ngFor="let cell of row[1] | orderBy: currShift"

https://stackblitz.com/edit/angular-lckecp

Answer №1

To solve the issue, a custom pipe was created. Many thanks to Amir for the helpful suggestion.

@Pipe({ name: 'orderByArray' })
export class OrderByArrayPipe implements PipeTransform {

    transform(array: Array<Cell>, orderByArray: Array<number>): Array<Cell> {

   var orderedArray = array.slice().sort(function (a, b) {
     return orderByArray.indexOf(a.hour) - orderByArray.indexOf(b.hour);
   });

   return orderedArray;
   }
}

It can be used in this way:

<ng-container *ngFor="let cell of row[1] | orderByArray: currShift.hours">

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

Issues with utilizing destructuring on props within React JS storybooks

I seem to be encountering an issue with destructuring my props in the context of writing a storybook for a story. It feels like there may be a mistake in my approach to destructuring. Below is the code snippet for my component: export function WrapTitle({ ...

In what way can a piped operator in rxjs be influenced by the value returned by a subsequent operator?

When attempting to examine values between operators in an rxjs pipe, I decided to use tap to log them to the console. I added two taps, one before a map operator used for sorting an Array, and one after. Surprisingly, both taps logged the same sorted Arra ...

Encountering a RangeError in Angular due to exceeding the maximum call stack size after removing distinctUntilChanged() from a formControl value change subscription

In the scenario where I have a parent and a child angular component, each containing their own set of form fields, I implemented change listeners in both components to monitor changes in form control values and disable certain fields based on user input. ...

The properties '{ label: string; value: string; }' are required in type 'readonly never[]' for react-select, but they are missing

state = { groupPermissionValue: {label: '', value: ''}, } <Select instanceId="user-group" onChange={this.selectUserGroupOption} value={this.state.groupPermissionValue} options={this.state.groupPermission} i ...

Running a Vue.js 3 application with TypeScript and Vite using docker: A step-by-step guide

I am currently facing challenges dockerizing a Vue.js 3 application using Vite and TypeScript. Below is my Dockerfile: FROM node:18.12.1-alpine3.16 AS build-stage WORKDIR /app COPY package.json ./ RUN yarn install COPY . . RUN yarn build-only FROM ngin ...

Encountering an Invalid JSON error on the Developer console

I'm in the process of building a React application and aiming to establish a connection with my Back4App database. Within the Back4App dashboard, there exists a Person class containing data that needs to be retrieved. It appears that the call is being ...

What are the steps for manually integrating Bootstrap into an Angular project?

I'm currently working on an Angular 5 project within a private domain where I am unable to utilize the npm-install command. As a result, I have manually added Bootstrap's CSS and JS files to my project. I am now unsure how to properly link these ...

Tips for handling callback responses from API POST requests in Node.js

I have integrated the following API Function into my project: The backend is built using NodeJS and the frontend with Angular. I am struggling to understand how the Callback in the function's POST request works. It seems to require a domain setup an ...

Hosting asynchronous bindings in Angular 2

I'm currently working on a component with the following code: @Component({ selector: 'my-selector', template: `<div>html code goes here</div> `, host: { '[style.background]': "'url(' ...

Steps to prevent uib-timepicker from automatically adjusting time based on the Browser Timezone

Currently in my database, timestamps are stored in UTC format. On the frontend, I am implementing uib-timepicker for time editing and updating purposes. However, I do not want uib-timepicker to automatically convert the time from the server's timezone ...

Resource Not Found (404 Error) Encountered While Loading (Material Design Lite)

Embarking on my first Angular 2 project and encountering some obstacles. Utilizing WebStorm as my IDE and generated the project using Angular CLI. Facing issues when integrating Material Design Lite into the application. Have imported the necessary depe ...

When using Google Chrome, you may encounter an error message stating that the 'Access-Control-Allow-Origin' header in the response cannot be set to a wildcard '*' even when a specific URL is specified

In my web application, I've utilized Angular 9 for the frontend and nodejs for the backend. The CORS middleware setup in my Express JS server is as follows: const corsOptions = { origin: [ "http://localhost:4200", ...

Testing the selection of dropdown values in Angular2 using unit tests

I have a dropdown menu for selecting countries. It defaults to a pre-selected value, and when the user changes it, they are redirected to the corresponding country page. However, I am facing an issue while trying to unit test the default value in the sele ...

I am experiencing difficulties with *ngIf in my HTML as it is not functioning properly, however, the ng

I have come across many inquiries related to this issue, but none of them proved helpful for me. Below is my HTML code: <div class="pl-lg-4"> <div *ngIf="isStorySelected; else hi" class="row"> ...

Angular - Evaluating the differences between the object model and the original model value within the view

To enable a button only when the values of the 'invoice' model differ from those of the initial model, 'initModel', I am trying to detect changes in the properties of the 'invoice' model. This comparison needs to happen in th ...

The EventEmitter in Angular 8 is prohibiting the emission of an Object

Is there a way I can emit an Object instead of primitive data types? I have an object const amount = { currenty: 'USD', total: '10.25' }; that I need to emit to the parent component. export class MyChildComponent implements OnInit { ...

How can you automate the process of skipping a protractor test?

Is there a way to skip protractor test cases based on certain conditions being true or false? I tried using pending('skipped'); expect(true).toBe(true); But it is marked as failed. Update I found a way to add test cases to "Pen ...

Issue with manipulating element styles using jQuery in Angular2

My method of assigning IDs to elements dynamically using *ngFor looks like this: <div *ngFor="let section of questionsBySubCat" class="col-md-12"> <div class="subcat-container"> <h4 class="sub-cat">{{ section?.subcategory }}& ...

The ng-model-options in Angular 2 is set to "updateOn: 'change blur'"

Currently working with angular 2, I am seeking a solution to modify the behavior of ngModel upon Enter key press. In angular 1.X, we utilized ng-model-options="{updateOn: 'change blur'}". How can this be achieved in angular 2? For reference, her ...

Exploring the world of functional programming in Java can be a rewarding experience, especially

I am seeking a method to define generic computation on a data set and have the compiler alert me if there are any errors. Having experience with TypeScript, I have seen that you can achieve something like this: /** * Type inferred as: * Array<{ * ...