[英]ramda.js how to do the groupby, count, sort
我有一個數據收集,例如:
[{"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"))
,但我無法弄清楚按計數進行排序的方式。
Create a function with R.pipe, that uses R.countBy to get an object of { [id]: count }
, then converts the data to pairs, and generate an array of objects with R.map, and 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>
顯然,如果您使用 Ramda, countBy
將成為解決方案的一部分。 然后我會選擇 pipe 到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
接受一個屬性名稱數組和一個值數組,並將它們一起壓縮成一個 object。
使用 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.