[英]JavaScript - Group array of objects into sub-arrays based on multiple properties
[英]Ramda JS partition array into multiple sub-arrays based on indices
我想获取一个数组并将其拆分为基于另一个索引数组的子数组字典:
const arr = ["A", "B", "C", "D", "E"];
const indices = [0, 0, 1, 0, 3];
// Would like to do something like this:
R.split(indices, array) // { "0": ["A", "B", "D"], "1": ["C"], "3": ["E"] }
在 Ramda 中有一种优雅的方法可以做到这一点吗?
使用R.zip
将 arrays 组合成值/索引对数组。 按索引分组,然后仅从对中取值:
const { pipe, zip, groupBy, last, map, head } = R const fn = pipe( zip, // combine the arrays to an array of value/indice pairs groupBy(last), // group by the indices map(map(head)) // take only the values from the pairs ) const arr = ["A", "B", "C", "D", "E"] const indices = [0, 0, 1, 0, 3] const result = fn(arr, indices) console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.