Answer the question
In order to leave comments, you need to log in
How to find the maximum date from an array?
Based on the condition, how to display one value at a certain interval. All users currently displayed if user.date
less than or equal to report.report_date
. But we need to display only the user who will be closest to the value in the interval. That is, how to display the maximum date for user.date
in order for the condition to work.
<div *ngFor="let report of reports">
<div *ngFor="let user of users">
<div *ngIf="report.users_id==user.user_id">
<div *ngIf="report.report_date >= user.date">
{{user.name}}
</div>
</div>
</div>
</div>
users: User[]
reports: Report[]
private loadUsers() {
this.usersService.fetch().subscribe(
users => {
this.users = users;
}
);
}
private loadReports() {
this.reportsService.fetch().subscribe(
reports => {
this.reports = reports
}
)
}
Answer the question
In order to leave comments, you need to log in
Maybe something like this, but I haven't tested it.
// шаблон
<div *ngFor="let user of reportsWithUser$|async">
{{user.name}}
</div>
//компонент
import {Observable} from "rxjs";
import {map, switchMap} from "rxjs/operators";
import * as _ from 'underscore';
interface User {
user_id: number;
name: string;
date: string;
}
interface Report {
report_date: string;
users_id: number;
}
interface UserWithReports extends User {
reports: Report[];
reportWithMaxDate: Report;
}
export function assignReportToUser(user: User, reports: Report[]): UserWithReports {
const repFiltered = reports.filter(report => report.report_date >= user.date);
return {...user, reports: repFiltered.filter(report => report.users_id === user.user_id), reportWithMaxDate: _.max(repFiltered, (r) => r.report_date)};
}
export class AnyComponent {
reportsWithUser$: Observable<UserWithReports[]>;
constructor(
public reportsService: any,
public usersService: any
) {
this.reportsWithUser$ = this.reportsService.fetch().pipe(
switchMap((reports: Report[]) => this.usersService.fetch().pipe(
map((users: User[]) => {
return users.map(user => assignReportToUser(user, reports)).filter((user) => user.reportWithMaxDate !== null);
})
)
)
)
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question