如何使用 Ramda 计算数组中的重复项?

Kri*_*ova 3 javascript arrays ramda.js

我有一个包含重复值的数组,我需要使用 ramda.js 找出每个值在数组中出现的次数。

这是我的数组: [2013, 2013, 2013, 2014, 2014, 2014, 2014, 2015, 2015, 2015, 2015, 2015, 2015, 2015, 2016, 2016, 2014, 2014, 2015, 2015, 2015, 2015, 2016, 2016, 16, 200, 16, 200, 16, 20, 20

这就是我想从中得到的: [3, 4, 7, 5, 3]

下面是它如何在纯 JavaScript 中工作的示例。

function count (arr) {
  const counts = {}
  arr.forEach((x) => { counts[x] = (counts[x] || 0) + 1 })
  return Object.values(counts)
}
Run Code Online (Sandbox Code Playgroud)

Ori*_*ori 5

假设(就像在您的代码中一样)重复项不必按顺序排列,您可以使用R.countBy()and获得相同的结果R.values()

const { pipe, countBy, identity, values } = R;

const arr = [2013, 2013, 2013, 2014, 2014, 2014, 2014, 2015, 2015, 2015, 2015, 2015, 2015, 2015, 2016, 2016, 2016, 2016, 2016, 2017, 2017, 2017]

const countDupes = pipe(
  countBy(identity),
  values
)

console.log(countDupes(arr));
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
Run Code Online (Sandbox Code Playgroud)