gpt4 book ai didi

javascript - 按属性使用 ramda 组并对指定属性求和结果

转载 作者:数据小太阳 更新时间:2023-10-29 06:09:48 24 4
gpt4 key购买 nike

我需要帮助使用 ramda 转换对象数组;我愿意

  1. 按指定属性分组
  2. 对另一个属性求和结果集

给定一个这样的数组:

var arr = [
{
title: "scotty",
age: 22,
score: 54,
hobby: "debugging"

}, {
title: "scotty",
age: 22,
score: 19,
hobby: "debugging"
}
, {
title: "gabriel",
age: 40,
score: 1000
}
];

如果我想按 title 分组并按 age 求和,它应该返回以下值摘要

var arr = [
{
title: "scotty",
age: 44,
hobby: "debugging",
}
, {
title: "gabriel",
age: 40,
score: 1000
}
];

当未指定属性的值不同时,应将其省略,但如果未指定属性的值相同,则应保留在最终结果中。

** 我的解决方案 **

    /*
* [Student]
*/
var arr = [
{
title: "scotty",
age: 22,
score: 54,
hobby: "debugging"

}, {
title: "scotty",
age: 22,
score: 19,
hobby: "debugging"
}
, {
title: "gabriel",
age: 40,
score: 1000
}
];


/*
* String -> [[Student]] -> [Student]
*/
var sumOnProperty = function(property, v){
var sum = (x,y) => x[property] + y[property];
var new_array = [];
v.forEach(arr => {
if(arr.length > 1){
arr[0]["age"] = arr.reduce(sum)
new_array.push(arr[0]);
} else {
if(arr.length != 0){
new_array.push(arr[0]);
}
}
})
return new_array;
}

/*
* String -> String -> [Student] -> [Student]
*/
var groupsumBy = function(groupproperty, sumproperty, arr){

// create grouping
var grouping = R.groupBy(R.prop(groupproperty), arr)

// convert grouping object to array
var result1 = R.valuesIn(grouping);

// sum each grouping and flatten 2d array
var result2 = sumOnProperty(sumproperty, result1);

return result2;
}


groupsumBy("title","age",arr);

最佳答案

修复您的 groupBy问题,您需要看到 groupBy 采用 key 生成函数而不是二元谓词。

例如,

const byTitle = R.groupBy(R.prop('title'));

这应该可以帮助您完成当前的障碍。如果您在求和方面需要帮助,请告诉我。

更新:

你问我的方法。它确实和你的有点不同。我可能会做这样的事情:

const sumBy = prop => vals => reduce(
(current, val) => evolve({[prop]: add(val[prop])}, current),
head(vals),
tail(vals)
)
const groupSumBy = curry((groupOn, sumOn, vals) =>
values(map(sumBy(sumOn))(groupBy(prop(groupOn), vals)))
)

groupSumBy('title', 'age', people)

或者如果我想让它更简洁一点,我可能会切换到:

const sumBy = prop => lift(
reduce((current, val) => evolve({[prop]: add(val[prop])}, current)
))(head, tail)

请注意,sumBy 相对可重用。它并不完美,因为它会在空列表上失败。但在我们的例子中,我们知道 groupBy 的输出永远不会为键创建这样一个空列表。任何没有在空列表上失败的版本都需要一种方法来提供默认情况。它只会变得丑陋。

你可以在 Ramda REPL 上看到这个 Action .

您可以使用 pipe 制作一个更易于阅读的 groupSumBy 版本或 compose如果您愿意首先使用 groupOnsumOn 值调用,然后使用这些值调用结果函数,也就是说,如果调用如下所示:

groupSumBy('title', 'age')(people)
// or more likely:
const foo = groupSumBy('title', age)
foo(people)

但我将其作为练习留给读者。

关于javascript - 按属性使用 ramda 组并对指定属性求和结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45739479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com