我在一個陣列里有這樣的字串:
我在一個陣列里有這樣的字串。
let arr = ["UserA | 3"/span>, "UserB | 0"/span>, "UserC | 2"/span>, "UserD | 1"/span>]
名字和他們的ID在最后。我想在最后根據他們的ID進行排序,但是沒有辦法做到這一點。
uj5u.com熱心網友回復:
你可以使用String#split和Array#sort,在這個方案中定義一個自定義的compareFunction函式來完成:
MDN Web 檔案:
- 如果
compareFunction(a, b)回傳的值>大于0,則將b排序在a之前。- 如果
compareFunction(a, b)回傳的值<比0,將a排序在b之前。- 如果
compareFunction(a, b)回傳0,a和b被認為是相等的。
像這樣:
。let arr = ["UserA | 3", "UserB | 0"/span>, "UserC | 2"/span>, "UserD | 1"/span>, "UserE | 2020"/span>] 。
arr.sort((a, b) => a。 split(" | ")[1] - b。 split(" | ")[1])。)
console.log(arr);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
uj5u.com熱心網友回復:
你可以使用RegExp結合String.prototype.match()創建一個函式來提取最后的數字id:
常規運算式。/d (?=D*$)/
- d匹配一個數字(相當于[0-9])
- 匹配1到無限次之間的前一個令牌,盡可能多的次數,根據需要給予回報(貪婪)
- 正數看頭 (?=D*$) 斷言下面的Regex匹配 D 匹配任何非數字的字符(相當于 [^0-9])
- * 匹配0到無限次之間的前一個標記,盡可能多的次數,根據需要給予回饋(貪婪) 。
- $斷定位置在字串的末尾,或者在字串末尾的行終止符之前(如果有的話)
代碼:
。const arr = ["UserE | 2020", "UserA | 3"/span>, "UserB | 0"/span>, "UserC | 2"/span>, "UserD | 1"/span>]
const getId = s => s. match(/d (?=D*$)/) [0]
arr.sort((a, b) => getId(a) - getId(b)
console.log(arr)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" class="snippet-box-edit snippet-box-result" frameborder="0"></iframe>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/307852.html
標籤:
