[英]Re-Map an array of Object based on sort order of a property
讓我們看看我有以下結構的數據
[
{
"Id": "xyz7",
"CurrentRow": 0,
"ReportTime": "2022-07-18T09:00:00+00:00",
"ExitTime": null,
"DateField": "2022-07-18"
},
{
"Id": "xyz8",
"CurrentRow": 1,
"ReportTime": "2022-07-18T08:00:00+00:00",
"ExitTime": null,
"DateField": "2022-07-18"
},
{
"Id": "wxyz0",
"CurrentRow": 0,
"ReportTime": "2022-07-19T00:00:00+00:00",
"ExitTime": null,
"DateField": "2022-07-19"
},
{
"Id": "wxyz1",
"CurrentRow": 1,
"ReportTime": "2022-07-19T00:00:00+00:00",
"ExitTime": null
"DateField": "2022-07-19"
}
]
如果我不得不說根據 ReportTime of Date: 2022-07-18 對結構進行排序,這會將 DateField 2022-07-18 的條目的 CurrentRow 更改為 0 到 1(因為它現在屬於第一個索引)和第二個條目 1 - 0。
另外,其他條目的CurrentRow(對於其他日期,如果與被排序的日期相同,也要進行調整。)
為了實現這一點,我的實現是這樣的,
我將結構轉換為基於 CurrentRow 的二維數組。
維度 1 中的索引,表示 CurrentRow。 數組的元素將是一個特定數據條目的數組,例如[entry_for_date_18,entry_for_date_19]
(一種以日期為列,以 CurrentRow 為行的電子表格。
然后為了進行排序,我選擇了特定日期的所有條目,對其進行排序,然后將其與原始 CurrentRow 一起收集。 (通過 1)。
然后我 go 並使用索引(通過 2)更新原始數組的 CurrentRow。
例如偽代碼:
for(let i=0;i<sortedDayArray.length;i++){
findByInOriginalArray(sortedDayArray[i].CurrentRow).updateCurrentRowTo(i)
}
想知道是否有更好或更有效的方法來做到這一點,使用 map?
這就是我得到您的問題的方式:您想根據ReportTime
對數組進行排序,然后根據DateField
中的 position 重新排列CurrentRow
,這是您期望的數據:
[
{
Id: 'xyz8',
CurrentRow: 0,
ReportTime: '2022-07-18T08:00:00+00:00',
ExitTime: null,
DateField: '2022-07-18'
},
{
Id: 'xyz7',
CurrentRow: 1,
ReportTime: '2022-07-18T09:00:00+00:00',
ExitTime: null,
DateField: '2022-07-18'
},
{
Id: 'wxyz0',
CurrentRow: 0,
ReportTime: '2022-07-19T00:00:00+00:00',
ExitTime: null,
DateField: '2022-07-19'
},
{
Id: 'wxyz1',
CurrentRow: 1,
ReportTime: '2022-07-19T00:00:00+00:00',
ExitTime: null,
DateField: '2022-07-19'
}
]
這是我想出的代碼:
var tempRow = 0;
var tempDate = ''
YOUR_ARRAY
.sort((a, b) => (a.ReportTime > b.ReportTime) ? 1 : ((b.ReportTime > a.ReportTime) ? -1 : 0))
.forEach((row, i) => {
if (row.DateField != tempDate) {
tempDate = row.DateField
tempRow = 0
}
row.CurrentRow = tempRow
tempRow++
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.