gpt4 book ai didi

javascript - 使用 javascript 根据键对数组中的值进行分组

转载 作者:行者123 更新时间:2023-11-28 14:35:09 25 4
gpt4 key购买 nike

我有以下数组值,

[
{
"amount": 4.27,
"month": 1,
"year": 2017
},
{
"amount": 2.46,
"month": 1,
"year": 2017
},
{
"amount": 1.5,
"month": 2,
"year": 2017
},
{
"amount": 28.24,
"month": 2,
"year": 2017
},
{
"amount": 8.24,
"month": 3,
"year": 2017
},
{
"amount": 3.65,
"month": 3,
"year": 2017
},
{
"amount": 0.86,
"month": 3,
"year": 2017
},
{
"amount": 0,
"month": 1,
"year": 2018
},
{
"amount": 71.84,
"month": 2,
"year": 2018
},
{
"amount": 26.62,
"month": 3,
"year": 2018
}]

必须根据特定的进行分组,最终值应采用以下格式,

[
{
"amount": 6.63,
"month": 1,
"year": 2017
},
{
"amount": 29.74,
"month": 2,
"year": 2017
},
{
"amount":12.75,
"month": 3,
"year": 2017
},
{
"amount": 0,
"month": 1,
"year": 2018
},
{
"amount": 71.84,
"month": 2,
"year": 2018
},
{
"amount": 26.62,
"month": 3,
"year": 2018
}]

我引用了这个例子:Group array items using object

但是我无法整理出求和部分,我得到的只是特定月份和年份的第一个值。

最佳答案

使用reduceObject.valuessort

var fnGetKey = (obj) => JSON.stringify({year:obj.year, month:obj.month}); //get key from object
Object.values(arr.reduce( (a,c) => {
var key = fnGetKey( c );
!a[key] ? (a[key] = c) : (a[key].amount += c.amount); //Initialize with c if key doesn't exists in accumulator, else increment amount
return a; //return accumulator
} ,{})).sort( (a,b) => a.year - b.year || a.month - b.month ); //sort by year and month

演示

var arr = [{
"amount": 4.27,
"month": 1,
"year": 2017
},
{
"amount": 2.46,
"month": 1,
"year": 2017
},
{
"amount": 1.5,
"month": 2,
"year": 2017
},
{
"amount": 28.24,
"month": 2,
"year": 2017
},
{
"amount": 8.24,
"month": 3,
"year": 2017
},
{
"amount": 3.65,
"month": 3,
"year": 2017
},
{
"amount": 0.86,
"month": 3,
"year": 2017
},
{
"amount": 0,
"month": 1,
"year": 2018
},
{
"amount": 71.84,
"month": 2,
"year": 2018
},
{
"amount": 26.62,
"month": 3,
"year": 2018
}
];

var fnGetKey = (obj) => JSON.stringify({
year: obj.year,
month: obj.month
}); //get key from object


var output = Object.values(arr.reduce((a, c) => {
var key = fnGetKey(c);
!a[key] ? (a[key] = c) : (a[key].amount += c.amount);
return a;
}, {})).sort((a, b) => a.year - b.year || a.month - b.month);

console.log(output);

关于javascript - 使用 javascript 根据键对数组中的值进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50036202/

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