嘗試對此字串陣列進行排序/排序時遇到一些問題。回應中回傳了數千個檔案名,下面是 10 個的示例。
array = [
'ORDERHEADER_010122.arc',
'ORDERITEM_010122.arc',
'ORDERDETAIL_010122.arc',
'ORDERDETAIL_010222.arc',
'ORDERDETAIL_010322.arc',
'ORDERHEADER_010222.arc',
'ORDERHEADER_010322.arc',
'ORDERHEADER_010422.arc',
'ORDERITEM_010222.arc',
'ORDERDETAIL_010422.arc'
];
一個簡單array.sort()的方法解決了一半的問題,因為它將按字母順序排列字串并固有地對日期進行排序。
我需要的是一種“順序”順??序以及日期順序。我prioSequence = ['ORDERHEADER', 'ORDERDETAIL', 'ORDERITEM'];想看到的順序也是如此。
預期輸出為:
array = [
'ORDERHEADER_010122.arc',
'ORDERDETAIL_010122.arc',
'ORDERITEM_010122.arc',
'ORDERHEADER_010222.arc',
'ORDERDETAIL_010222.arc',
'ORDERITEM_010222.arc',
'ORDERHEADER_010322.arc',
'ORDERDETAIL_010322.arc',
'ORDERHEADER_010422.arc',
'ORDERDETAIL_010422.arc'
];
任何幫助/指導將不勝感激!謝謝!
uj5u.com熱心網友回復:
在字串前面加上確定排序的部分,即 yymmdd 和“ORDER”字串中的 2 個字母,因為事實證明,當您選擇這些單詞(EA、ET、TE)的第 7 個和第 8 個字母時,它們將是正確排序。然后在對專案進行排序后,再次洗掉該前綴。
這是如何運作的:
let array = [
'ORDERHEADER_010122.arc',
'ORDERITEM_010122.arc',
'ORDERDETAIL_010122.arc',
'ORDERDETAIL_010222.arc',
'ORDERDETAIL_010322.arc',
'ORDERHEADER_010222.arc',
'ORDERHEADER_010322.arc',
'ORDERHEADER_010422.arc',
'ORDERITEM_010222.arc',
'ORDERDETAIL_010422.arc'
];
let sorted = array.map(item =>
item.replace(/ORDER.(..).*?_(..)(..)(..).*/g, "$4$3$2$1") item
).sort().map(s => s.slice(8));
console.log(sorted);
擴展它
如果您有更多要控制順序的前綴詞,則按預期順序創建一個陣列。然后,該解決方案將該陣列轉換為查找映射(為給定單詞提供 4 個字符的序列號)。呼叫replacethen 需要一個回呼引數,它將進行查找并為該序列添加前綴。這是代碼:
let array = [
'ORDERHEADER_010122.arc',
'ORDERITEM_010122.arc',
'ORDERDETAIL_010122.arc',
'ORDERDETAIL_010222.arc',
'ORDERDETAIL_010322.arc',
'ORDERHEADER_010222.arc',
'ORDERHEADER_010322.arc',
'ORDERHEADER_010422.arc',
'ORDERITEM_010222.arc',
'ORDERDETAIL_010422.arc'
];
let priorities = [
'ORDERHEADER',
'ORDERDETAIL',
'ORDERITEM',
];
// Map the priority array to an object for faster look-up
let priMap = Object.fromEntries(priorities.map((word, i) =>
[word, ("000" i).slice(-4)]
));
let sorted = array.map(item =>
item.replace(/(.*?)_(..)(..)(..).*/g, (all, word, dd, mm, yy) =>
yy mm dd (priMap[word] ?? "----") all
)
).sort().map(s => s.slice(10));
console.log(sorted);
uj5u.com熱心網友回復:
您必須為排序方法呼叫定義自定義比較函式。而且,該方法應首先比較日期,然后(如果日期相同)根據您的要求訂購前綴
這是我的例子
const order = new Map() // one can use plain Array Array#indexOf later on
.set('ORDERHEADER', 0)
.set('ORDERDETAIL', 1)
.set('ORDERITEM', 2)
const compareFn = (a, b) => {
const [a1, a2] = a.split('_')
const [b1, b2] = b.split('_')
const r2 = a2.localeCompare(b2)
if (r2 !== 0) return r2
return order.get(a1) - order.get(b1) // or Array#indexOf as mentioned above
}
// usage
array.sort(compareFn)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441063.html
標籤:javascript 数组 排序
上一篇:不確定如何按日期對2djavascript陣列進行排序
下一篇:簡單選擇排序不會排序
