我有一個將整數映射到月份標簽的函式
// Get month label
getMonthName(monthNumber: any): string {
var tempMonth: string;
let monat = [
{ id: 1, title: 'Januari' },
{ id: 2, title: 'Februari' },
{ id: 3, title: 'Maart' },
{ id: 4, title: 'April' },
{ id: 5, title: 'Mei' },
{ id: 6, title: 'Juni' },
{ id: 7, title: 'Juli' },
{ id: 8, title: 'Aout' },
{ id: 9, title: 'Sept' },
{ id: 10, title: 'Oct' },
{ id: 11, title: 'Nov' },
{ id: 12, title: 'Dec' },
];
monat.forEach((yue) => {
if (yue.id === monthNumber) {
tempMonth = yue.title;
}
});
return tempMonth;
}
然后我從這個函式呼叫它
// Get the data from service
getConso() {
this.consosrv.getConso().subscribe((tempo: Conso[]) => {
this.TheConso = tempo;
//Group data in month
const groups = this.TheConso.reduce((groups, donne) => {
const month = new Date(donne.date_achat).getMonth() 1;
const MM = this.getMonthName(month);
if (!groups[MM]) {
groups[MM] = [];
}
groups[MM].push(donne);
return groups;
}, {});
//Mapping data to array
this.groupArrays = Object.keys(groups).map((mois) => {
return {
mois,
sum: groups[mois].reduce((a, b) => a parseInt(b.food_prix), 0),
donnes: groups[mois].sort(
(objA, objB) =>
new Date(objA.date_achat).getTime() -
new Date(objB.date_achat).getTime()
),
};
});
});
}
如果我使用
const month = new Date(donne.date_achat).getMonth() 1;
它作業,它以整數排序。
但我想按字母排序
const MM = this.getMonthName(month);
我實作了你的代碼,但它不太好用:

uj5u.com熱心網友回復:
如果我理解正確并且您想按月份名稱對 groupArrays 串列進行排序,您可以這樣做:
this.groupArrays = Object.keys(groups).map((mois) => {
return {
...
};
}).sort((a, b) => a.mois.localCompare(b.mois))
作為旁注,有更簡潔的方法來獲取月份的名稱。例如,您可以使用從 @angular/common 匯入的日期管道 (formatDate) 使用的函式,或者如果您使用的是 date-fns 之類的庫:
format(new Date(), 'MMMM', { locale: de })
另外,我建議避免手動訂閱并使用異步管道。
編輯
要從下面回答您的問題,如果您想將月份用作整數并顯示相應的月份標簽,您可以創建一個自定義管道。
假設您的物件看起來像這樣:
{
monthId: 1,
sum: ...,
dones: ...
}
您的管道將是:
// be careful here, if you use the JS month number, you need to start
// indexing from 0
// Ex: 0 month is January
const dictionary: Record<number, string> = {
1: "Januari",
2: "Februari",
3: "Maart",
4: "April",
5: "Mei",
6: "Juni",
7: "Juli",
8: "Aout",
9: "Sept",
10: "Oct",
11: "Nov",
12: "Dec"
};
@Pipe({
name: "monthLabel"
})
export class MonthLabelPipe implements PipeTransform {
transform(value: number): string {
return dictionary[value];
}
}
你會像這樣使用它:
<span>{{ payload.monthId | monthLabel }}</span>
我希望這對你有幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/511582.html
標籤:有角度的排序离子框架
