You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Ramda的sortBy函数按嵌套children数量排序对象数组

使用Ramda按children数量排序对象数组

要实现按对象的children数组长度排序,核心是给R.sortBy传入一个能提取排序依据的函数,具体实现如下:

1. 示例数据

const data = [
  {
    "name": "Felicia",
    "age": "60",
    "children": [
      { "name": "Adrian", "age": "4" },
      { "name": "Joseph", "age": "5" }
    ]
  },
  {
    "name": "Alicia",
    "age": "43",
    "children": [
      { "name": "Billy", "age": "3" },
      { "name": "Mary", "age": "8" },
      { "name": "john", "age": "12" }
    ]
  }
];

2. 升序排序实现

利用Ramda的函数组合能力,先提取对象的children属性,再获取数组长度,最后传入R.sortBy完成排序:

const sortedAsc = R.sortBy(
  R.compose(R.length, R.prop('children'))
)(data);
  • R.prop('children'):从每个对象中取出children数组
  • R.length:计算数组的元素数量
  • R.compose:将两个函数组合成“取children→算长度”的流程
  • R.sortBy:基于这个流程返回的长度值,对数组进行升序排序

3. 降序排序实现

如果需要降序排列,可使用R.sortWith搭配R.descend:

const sortedDesc = R.sortWith([
  R.descend(R.compose(R.length, R.prop('children')))
])(data);

内容的提问来源于stack exchange,提问作者user12494839

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 11:22:15