gos*_*eti 4 javascript functional-programming ramda.js
我收集了如下所示的UNIX时间戳:
[
{"start_time":1540458000000, "end_time":1540472400000},
{"start_time":1540458000000, "end_time":1540486800000},
{"start_time":1540458000000, "end_time":1540501200000},
{"start_time":1540472400000, "end_time":1540486800000},
{"start_time":1540472400000, "end_time":1540501200000},
{"start_time":1540486800000, "end_time":1540501200000}
]
Run Code Online (Sandbox Code Playgroud)
我想从两个挑选出所有的独特的价值观start_time和end_time,所以我留下了:
[
{"start_time":1540458000000},
{"start_time":1540472400000},
{"start_time":1540486800000}
{"end_time":1540472400000},
{"end_time":1540486800000},
{"end_time":1540501200000},
]
Run Code Online (Sandbox Code Playgroud)
我看使用类似的东西使用groupBy,pluck,zipObj多使用的答案在这里。但不幸的是没有运气。
最好的是ramda函数,该函数无需指定特定键即可工作。
Ramda的另一种方法:
const {pipe, map, toPairs, unnest, groupBy, head, uniqBy, last, values, apply, objOf} = R
const uniqTimes = pipe(
map(toPairs), //=> [[['start', 1], ['end', 2]], [['start', 1], ['end', 3]], ...]
unnest, //=> [['start', 1], ['end', 2], ['start', 1], ['end', 3], ...]
groupBy(head), //=> {start: [['start', 1], ['start', 1], ['start', 4], ...], end: [['end', 2], ...]}
map(uniqBy(last)), //=> {start: [['start', 1], ['start', 4], ...], end: [['end', 2], ...]}
values, //=> [[['start', 1], ['start', 4], ...], [['end', 2], ...]]
unnest, //=> [['start', 1], ['start', 4], ..., ['end', 2], ...]
map(apply(objOf)) //=> [{"start": 1}, {"start": 4}, ..., {"end": 2}, ...]
)
const timestamps = [{"start_time":1540458000000,"end_time":1540472400000},{"start_time":1540458000000,"end_time":1540486800000},{"start_time":1540458000000,"end_time":1540501200000},{"start_time":1540472400000,"end_time":1540486800000},{"start_time":1540472400000,"end_time":1540501200000},{"start_time":1540486800000,"end_time":1540501200000}]
console.log(uniqTimes(timestamps))Run Code Online (Sandbox Code Playgroud)
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>Run Code Online (Sandbox Code Playgroud)
这就是我喜欢使用Ramda的方式:构建一个函数管道,每个函数都进行简单的转换。
有条评论询问如何生成更类似的输出
{
"start_time": [1540458000000, 1540458000000],
"end_time": [1540472400000, 1540486800000]
}
Run Code Online (Sandbox Code Playgroud)
对于相同的输入,应该这样做:
const uniqTimes = pipe(
map(toPairs),
unnest,
groupBy(head),
map(map(last)),
map(uniq)
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
923 次 |
| 最近记录: |