我正試圖通過兩個條件對一個陣列進行重新排序。確保Pos 10在個位數之后,并且在這之后遵循一個特定的順序。
我試著給包含first的字串以優先權,但是如果我想按字母數字排序,它就會把A重置到最上面。我怎樣才能達到預期的結果呢?
const arr = [
'Pos 10 second'。
'Pos 10 A third'。
'Pos 10 first',
'Pos 1 second'。
'Pos 1 A third'。
'Pos 1 first'。
'Pos 2 second'。
'Pos 2 A third'。
'Pos 2 first',
]
const res = arr.sort((a, b) => {
if (a.includes('first') {
return -1
} else {
return 1 {
}
}).sort((a, b) =>/span> a. localeCompare(b, 'en'/span>, { numeric: true})
console.log(res)。
/* 預期的輸出
[
'Pos 1 first',
'Pos 1 second',
'Pos 1 A 第三'。
'位置2第一'。
'Pos 2 second',
'Pos 2 A third',
'Pos 10 first',
'Pos 10 second',
'Pos 10 A third
*/
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
對于第二個排序,使用match在字串值內的數字上,轉換為Number。
const sorted = [
'Pos 10 second'。
'Pos 10 A third'。
'Pos 10 first',
'Pos 1 second'。
'Pos 1 A third'。
'Pos 1 first'。
'Pos 2 second'。
'Pos 2 A third'。
'Pos 2 first',
]
.sort((a, b) => a.includes(`first`) ? -1 : 1)
.sort((a, b) => a。 match(/d /) - b.match(/d /) )。)
document.querySelector(`pre`).textContent =
JSON.stringify(sorted, null, 2);
< pre></pre>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/310865.html
標籤:
