如何使用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
相关产品推荐
相关产品推荐

