2 回答

TA貢獻1772條經驗 獲得超8個贊
以下代碼將有所幫助:
this.postService.getDetails().subscribe(
response => {
let sortedData= response.data.history
.sort(function(a, b) {
return new Date(b.date) - new Date(a.date);
}); //Sort based on date
sortedData.forEach(item=>item.statewise.sort(function(a, b) {
if (a.state < b.state) {
return -1;
}
if (a.state > b.state) {
return 1;
}
return 0;
})); //sort state wise in alphabetical order
console.log(sortedData);
this.loading = false;
},
error => {
console.log(error);
this.loading = false;
}
);
示例演示:
https://stackblitz.com/edit/angular-rxjs-operators-examples?file=src%2Fapp%2Fstackoverflow%2Fmerge-map-error%2Fmerge-map-error.component.ts
https://angular-rxjs-operators-examples.stackblitz.io/stackoverflow
在控制臺中查找已排序的數據。

TA貢獻1850條經驗 獲得超11個贊
您可以使用sort數組的原型來做到這一點。
let records = {
"history": [
{
"day": "2020-03-14",
"total": {
"confirmed": 84
},
"statewise": [
{
"state": "Kerala",
"confirmed": 19
},
{
"state": "Assam",
"confirmed": 14
}
]
},
{
"day": "2020-03-15",
"total": {
"confirmed": 104
},
"statewise": [
{
"state": "Kerala",
"confirmed": 119
},
{
"state": "Assam",
"confirmed": 114
}
]
}
]
};
const res = {history: []};
res.history = records.history.map(history => {
history.statewise.sort((a, b) => a.state < b.state ? -1 : 1);
return history;
});
console.log(res);
.as-console-wrapper {
min-height: 100% !important;
}
添加回答
舉報