我有一个数组数组,并且想编写一个函数,该函数通过按顺序从每个数组中获取项目来返回最上面的x
项数。
这是我所追求的一个例子:
const input = [
["1a", "2a", "3a", "4a", "5a"],
["1b", "2b", "3b", "4b", "5b"],
["1c", "2c", "3c", "4c", "5c"],
["1d", "2d", "3d", "4d", "5d"]
];
const takeRoundRobin = count => arr => {
// implementation here
};
const actual = takeRoundRobin(5)(input);
const expected = [
"1a", "1b", "1c", "1d", "2a"
];
我看到一个有关Scala问题的建议,该问题使用
zip
解决了这一问题,但在Ramda中,您只能将2个列表传递给zip。 最佳答案
在这里,Ramda的 transpose
可以成为您的基础。添加一团 unnest
,一点点 take
,您会得到:
const {take, unnest, transpose} = R
const takeRoundRobin = (n) => (vals) => take(n, unnest(transpose(vals)))
const input = [
['1a', '2a', '3a', '4a', '5a'],
['1b', '2b', '3b', '4b', '5b'],
['1c', '2c', '3c', '4c', '5c'],
['1d', '2d', '3d', '4d', '5d']
]
console.log(takeRoundRobin(5)(input))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
还要注意,这可以处理不同长度的数组:
如果您希望能够重新开始并继续使用值,则可以将
take
替换为recursiveTake
,如下所示:const {take, unnest, transpose, concat } = R
//recursive take
const recursiveTake = (n) => (vals) => {
const recur = (n,vals,result) =>
(n<=0)
? result
: recur(n-vals.length,vals,result.concat(take(n,vals)))
return recur(n,vals,[]);
};
const takeRoundRobin = (n) => (vals) =>
recursiveTake(n)(unnest(transpose(vals)));
const input = [
['1a', '2a', '3a', '4a'],
['1b'],
['1c', '2c', '3c', '4c', '5c'],
['1d', '2d']
]
console.log(takeRoundRobin(14)(input))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script>
没有显式递归的该函数的另一个版本如下所示:
const takeCyclic = (n) => (vals) => take(
n,
unnest(times(always(vals), Math.ceil(n / (vals.length || 1))))
)
关于javascript - 使用Ramda从多个阵列中轮流获取前X个项目,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52875280/