我在使用Ramda sortWith按多列(升序或降序)对深层嵌套的对象数组进行排序时遇到麻烦。显然,排序是区分大小写的,并导致将以小写字母开头的值放在排序数组的末尾。
首先我导入必要的ramda函数:
import { sortWith, path, useWith, split, ascend, descend } from 'ramda'
然后我有这个数组:
const theList = [
{
name: 'A',
purchase: {
period: {
start: '2020-01-08T21:00:00Z',
end: '3070-10-27T21:00:00Z',
},
},
},
{
name: 'b',
purchase: {
period: {
start: '2019-09-30T19:00:00Z',
end: '3070-10-27T21:00:00Z',
},
},
},
{
name: 'C',
purchase: {
period: {
start: '2020-01-26T21:00:00Z',
end: '3070-10-27T21:00:00Z',
},
},
},
]
为了进行排序,我使用了规则数组:
const sort = [
{ oder: 'asc', name: 'name' },
{ oder: 'desc', name: 'purchase.period.start' },
]
最后,我尝试使用给定的规则集对该数组进行排序:
const sortFunctions = sort.map(({ order, name }) => (
(order === 'asc')
? ascend(useWith(path, [split('.')])(name))
: descend(useWith(path, [split('.')])(name))
))
return sortWith(sortFunctions)(theList)
但是结果如下:
[
{
"name": "b",
"purchase": {
"period": {
"start": "2019-09-30T19:00:00Z",
"end": "3070-10-27T21:00:00Z"
}
}
},
{
"name": "C",
"purchase": {
"period": {
"start": "2020-01-26T21:00:00Z",
"end": "3070-10-27T21:00:00Z"
}
}
},
{
"name": "A",
"purchase": {
"period": {
"start": "2020-01-08T21:00:00Z",
"end": "3070-10-27T21:00:00Z"
}
}
}
]
所以这里的问题是b
不在中间,因为它考虑到了区分大小写的问题。不仅如此,列表还似乎与预期顺序相反。
我在这里做错什么了,我怎么能忽略大小写?
[您的代码版本略有更改(使用管道而不是useWith
,我希望尽量避免使用此代码,我们可以像这样在比较器中添加toLower
:
const makeSorter = compose (
sortWith,
map (({order, name}) => (order == 'desc' ? descend : ascend) (
compose (toLower, path (split ('.', name)))
))
)
const sorts = [
{ order: 'asc', name: 'name' },
{ order: 'desc', name: 'purchase.period.start' },
]
// Switched the order to make the sorting clear
const theList = [{name: "C", purchase: {period: {start: "2020-01-26T21: 00: 00Z", end: "3070-10-27T21: 00: 00Z"}}}, {name: "A", purchase: {period: {start: "2020-01-08T21: 00: 00Z", end: "3070-10-27T21: 00: 00Z"}}}, {name: "b", purchase: {period: {start: "2019-09-30T19: 00: 00Z", end: "3070-10-27T21: 00: 00Z"}}}]
console .log (
makeSorter (sorts) (theList)
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
<script> const {compose, sortWith, map, ascend, descend, toLower, path, split} = R </script>
我还将测试从asc
更改为desc
,因为我使用了类似的方法,其中asc
是默认值,而该字段是可选的。 (desc
在需要时是必需的。)
这只是避免了我们传递给ascend
或descend
的函数中的某些重复:
(order == 'desc' ? descend : ascend)
我还没有测试过它实际上可以用于多种类型,因为这些值在'name'上都不一致,但是看起来应该可以使用。