[英]How do I sort an array of strings numerically with Ramda?
我正在嘗試正確排序以下對象的鍵:
const data = {
'0 - 4': [...],
'5 - 9': [...],
'10 - 14': [...],
'15 - 19': [...],
};
通過做:
const sort = R.sortBy(R.toLower);
return R.compose(sort, R.keys)(data);
但它總是最終出現:
['0 - 4', '10 - 14', '15 - 19', '5 - 9'];
因為它將數字視為一個字符串,並且以 5 開頭的字符串據說比以 1 開頭的字符串要高。有人知道如何使用 Ramda 對其進行正確排序,以使其顯示為
['0 - 4', '5 - 9', '10 - 14', '15 - 19'];
您可以在比較器 function 中將String.localCompare()
與numeric: true
選項一起使用:
const data = { '0 - 4': [], '5 - 9': [], '10 - 14': [], '15 - 19': [], }; const sort = R.sort((a, b) => a.localeCompare(b, undefined, { numeric: true })); const result = R.compose(sort, R.keys)(data); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>
這就是沒有 Ramda 的情況:
const data = { '0 - 4': [], '5 - 9': [], '10 - 14': [], '15 - 19': [], }; const fn = obj => Object.keys(obj).sort((a, b) => a.localeCompare(b, undefined, { numeric: true })); const result = fn(data); console.log(result);
使用parseInt
代替R.toLower
:
const sort = R.sortBy(parseInt);
R.toLower
沒有意義,因為它無論如何都不會影響字符串,因為它們只包含數字、破折號和空格,並且調用toLower
的結果仍然是一個字符串,同一個字符串。
另一方面, parseInt
將返回每個字符串的左側數字(例如parseInt('10 - 14')
是數字10
,而不是字符串),然后sortBy
將使用該數字對字符串進行排序。
演示:
const data = { "10 - 14'": [], "5 - 9": [], "15 - 19": [], "0 - 4": [] }; const sort = R.sortBy(parseInt); const result = R.compose(sort, R.keys)(data); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js" integrity="sha512-rZHvUXcc1zWKsxm7rJ8lVQuIr1oOmm7cShlvpV0gWf0RvbcJN6x96al/Rp2L2BI4a4ZkT2/YfVe/8YvB2UHzQw==" crossorigin="anonymous"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.