我有一个随机的数字 1 到 5 数组,有时会随机出现 [1,1,1,1,2,2] 等。我的任务是始终找到出现次数最多的值。我在这里使用名为 ramda 的库在 javascript 中实现了这一点。阅读文档后,我采用了如下解决方案。
// filter out duplication in array that way you can get the uniq represented numbers
const uniqueItems = R.uniq(params);
// use the unique numbers as keys and create a new array of object
const mappedItemsWithRepresentations = map((a) => ({ color: a, rep: params.filter(b => b === a).length }), uniqueItems);
// and then finally, select the item with highest rep and return it key
const maxRepItem = mappedItemsWithRepresentations.reduce((acc, curr) => acc.rep > curr.rep ? acc : curr, []);
return maxRepItem.key; // gives me the correct value i need
但是,通过阅读更多文档并浏览此处的示例,我意识到有一种方法可以将上面的逻辑简单地与 ramda 结合起来。我尝试了无数次尝试,我能得到的最接近的是下面。
const getMaxRep = curry(pipe(uniq, map((a) => ({ color: a, rep: filter(b => b === a).length })), pipe(max(pathEq("rep")), tap(console.log))));
console.log("Max Rep here", getMaxRep(params));
我也尝试在这里使用缩减功能,但均无济于事。请我如何安排实现这一目标?任何帮助将不胜感激。