GroupBy并以无点样式减少对象数组

时间:2019-03-29 02:38:15

标签: javascript reduce ramda.js

我最近开始使用Ramda,试图找到一种无点方法来编写一种减少对象数组的方法。

这是对象数组:

const someObj = [
    {
        name: 'A',
        city: 1,
        other: {
            playtime: 30
        }
    },
    {
        name: 'B',
        city: 2,
        other: {
            playtime: 20
        }
    },
    {
        name: 'c',
        city: 1,
        other: {
            playtime: 20
        }
    }
];

我要尝试的是使用ramda来简化

{
    '1': {
        count: 2,
        avg_play_time: 20 + 30 / count
    },
    '2': {
        count: 1,
        avg_play_time: 20 / count
    }
}

我可以使用数组缩减方法来做到这一点,但不确定如何用ramda pointfree样式编写同样的内容。任何建议将不胜感激。

5 个答案:

答案 0 :(得分:4)

一种解决方案是做这样的事情:

// An optic to extract the nested playtime value
// Coupled with a `lift` operation which allows it to be applied over a collection
// Effectively A -> B => A[] -> B[]
const playtimes = R.lift(R.path(['other', 'playtime']))

R.pipe(
  // Group the provided array by the city value
  R.groupBy(R.prop('city')),
  // Return a body specification which computes each property based on the 
  // provided function value.
  R.map(R.applySpec({
    count: R.length,
    average: R.pipe(playtimes, R.mean)
  }))
)(someObj)

答案 1 :(得分:2)

Ramda还具有另一个名为R.reduceBy的功能,该功能在reducegroupBy之间提供了一些功能,使您可以将匹配键一起折叠起来的值。

因此,您可以创建类似以下的数据类型,以将值进行平均计算。

const Avg = (count, val) => ({ count, val })
Avg.of = val => Avg(1, val)
Avg.concat = (a, b) => Avg(a.count + b.count, a.val + b.val)
Avg.getAverage = ({ count, val }) => val / count
Avg.empty = Avg(0, 0)

然后使用R.reduceBy将它们组合在一起。

const avgCities = R.reduceBy(
  (avg, a) => Avg.concat(avg, Avg.of(a.other.playtime)),
  Avg.empty,
  x => x.city
)

然后将平均值从Avg中提取为最终对象的形状。

const buildAvg = R.applySpec({
  count: x => x.count,
  avg_play_time: Avg.getAverage
})

最后通过管道将两者结合在一起,将buildAvg映射到对象中的值。

const fn = R.pipe(avgCities, R.map(buildAvg))
fn(someObj)

答案 2 :(得分:2)

这是另一个建议,使用reduceBy并在结果对象的每个属性上映射一个applySpec函数:

想法是使用someObjgetPlaytimeByCity转换为该对象:

{ 1: [30, 20],
  2: [20]}

然后,您可以将stats函数映射到该对象的每个属性上:

stats({ 1: [30, 20], 2: [20]});
// { 1: {count: 2, avg_play_time: 25}, 
//   2: {count: 1, avg_play_time: 20}}

const someObj = [
    { name: 'A',
      city: 1,
      other: { playtime: 30 }},
    { name: 'B',
      city: 2,
      other: { playtime: 20 }},
    { name: 'c',
      city: 1,
      other: { playtime: 20 }}
];

const city = prop('city');
const playtime = path(['other', 'playtime']);
const stats = applySpec({count: length, avg_play_time: mean});
const collectPlaytime = useWith(flip(append), [identity, playtime]);
const getPlaytimeByCity = reduceBy(collectPlaytime, [], city);

console.log(

  map(stats, getPlaytimeByCity(someObj))
  
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
<script>const {prop, path, useWith, flip, append, identity, applySpec, length, mean, reduceBy, map} = R;</script>

答案 3 :(得分:2)

我会这样写,希望对您有所帮助!

const stats = R.pipe(
  R.groupBy(R.prop('city')),
  R.map(
    R.applySpec({
      count: R.length,
      avg_play_time: R.pipe(
        R.map(R.path(['other', 'playtime'])),
        R.mean,
      ),
    }),
  ),  
);

const data = [
  { name: 'A', city: 1, other: { playtime: 30 } },
  { name: 'B', city: 2, other: { playtime: 20 } },
  { name: 'c', city: 1, other: { playtime: 20 } },
];

console.log('result', stats(data));
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>

答案 4 :(得分:1)

我喜欢到目前为止给出的所有其他答案。所以自然地我想添加自己的。 ;-)

这里是一个使用reduceBy来跟踪计数和均值的版本。如果您正在寻找中位数或其他统计信息,那么这将不起作用,但是如果给定一个计数,一个平均值和一个新值,我们可以直接计算新的计数和平均值。这样一来,我们就只能对数据进行一次迭代,而不必在每次迭代中都要做一些算术运算。

const transform = reduceBy(
  ({count, avg_play_time}, {other: {playtime}}) => ({
    count: count + 1,
    avg_play_time: (avg_play_time * count + playtime) / (count + 1)
  }),
  {count: 0, avg_play_time: 0},
  prop('city')
)
const someObj = [{city: 1, name: "A", other: {playtime: 30}}, {city: 2, name: "B", other: {playtime: 20}}, {city: 1, name: "c", other: {playtime: 20}}]

console.log(transform(someObj))
<script src="https://bundle.run/ramda@0.26.1"></script>
<script>
const {reduceBy, prop} = ramda
</script>

这不是没有意义的。尽管我非常喜欢无点样式,但是只有在适用时才使用它。我认为出于自身的原因而寻求它是一个错误。

请注意,斯科特·克里斯托弗(Scott Christopher)的答案可以很容易地修改为使用这种计算方式