首页 > 解决方案 > 对于数组中的重复值,如何在 Ramda.js 中使用“重复”

问题描述

我正在尝试target:[ "a", "b", "c"]复制count:[1, 2, 3]

理想的输出是["a", "b", "b", "c", "c", "c"]

它不适用于此代码:

const fn = ({ target, count }) => R.map (R.repeat (target, count))

const Data = { target : ["a", "b", "c"], count : [1, 2, 3] }

const result = fn(Data)

我正在尝试使用 Ramda.js 找到解决方案。

谢谢。

标签: ramda.js

解决方案


另一个相当简单的解决方案:

const fn = ({target, count}) => 
  unnest (zipWith (repeat) (target, count))

const data = {
  target: ['a', 'b', 'c'], 
  count: [1, 2, 3]
}

console .log (fn (data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.27.1/ramda.min.js"></script>
<script> const {unnest, zipWith, repeat} = R                             </script>

target和的无点函数data很简单:

compose (unnest, zipWith (repeat))

如果它们被包裹在一个对象中并且你真的想要无点,那么来自 Hitmands 的答案似乎是最好的,或者使用这种技术的变体:

compose (unnest, apply (zipWith (repeat)), props (['target', 'count']))

推荐阅读