我有一个数据集合,比如:
[{"id":1,"score":4},{"id":2,"score":3},{"id":1,"score":4},{"id":2,"score":3},{"id":3,"score":4},{"id":1,"score":3}]我希望输出如下:
[{"id":1,"count":3},{"id":2,"count":2},{"id":3,"count":1}]有没有什么解决方案可以使用Ramda.js来做到这一点?
我试着使用countBy(prop("id")),但我想不出按计数排序的方法。
发布于 2020-05-02 01:22:28
使用R.pipe创建一个函数,该函数使用R.countBy获取{ [id]: count }的对象,然后将数据转换为对,并使用R.map和R.applySpec生成对象数组。然后使用R.sortBy对其进行排序。
const { pipe, countBy, prop, toPairs, map, applySpec, head, last, sortBy, descend } = R
const fn = pipe(
countBy(prop('id')),
toPairs,
map(applySpec({
id: pipe(head, Number), // or just id: head if the id doesn't have to be a number
count: last,
})),
sortBy(descend(prop('count'))), // or ascend
)
const arr = [{"id":1,"score":4},{"id":2,"score":3},{"id":1,"score":4},{"id":2,"score":3},{"id":3,"score":4},{"id":1,"score":3}]
const result = fn(arr)
console.log(result)<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
发布于 2020-05-02 01:50:45
显然,如果您使用的是Ramda,那么countBy将是解决方案的一部分。然后,我会选择通过管道将其传递给toPairs和zipObj,以获得最终结果:
const collect = pipe (
countBy (prop ('id')),
toPairs,
map (zipObj (['id', 'count']))
)
const data = [{id: 1, score: 4}, {id: 2, score: 3}, {id: 1, score: 4}, {id: 2, score: 3}, {id: 3, score: 4},{id: 1, score: 3}]
console .log (collect (data))<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.27.0/ramda.js"></script>
<script> const {pipe, countBy, prop, toPairs, map, zipObj} = R </script>
zipObj接受一个属性名称数组和一个值数组,并将它们压缩成一个对象。
发布于 2020-05-02 01:09:37
使用vanillaJS,您可以简单地使用reduce和Map
const data = [{"id":1,"score":4},{"id":2,"score":3},{"id":1,"score":4},{"id":2,"score":3},{"id":3,"score":4},{"id":1,"score":3}]
const final = [...data.reduce((op,{id,score})=>{
if(op.has(id)){
op.set(id, op.get(id)+1)
} else {
op.set(id,1)
}
return op;
}, new Map()).entries()].map(([id,count])=>({id,count}))
console.log(final)
https://stackoverflow.com/questions/61547078
复制相似问题