Javascript数组:按唯一值和每个值的总和进行分组

Javascript arrays: group by unique values and sum-up amount per value

本文关键字:数组 唯一 Javascript      更新时间:2023-09-26

我试图建立自己的应用程序,我被困在一个问题,我无法解决。我的应用程序处理抵押贷款。我有好几笔按揭贷款同时进行,我只需要把每期的总还款额加起来。

假设我们有以下对象数组(即抵押):

[ {uptomonth:84 , payment:150} ] 
[ {uptomonth:120 , payment:200} ] 
[ {uptomonth:120 , payment:100} , {uptomonth:180 , payment:250} , {uptomonth:300 , payment:500} ] 

如何阅读这个(以第一行为例):"到第84个月为止,我每月支付150美元"

我想将数组组合成一个数组(例如使用array.concat…),然后按"uptommonth"排序对象,以获得这样的结果数组:

[ {uptomonth:84,payment:1200} , {uptomonth:120,payment:1050} , {uptomonth:180,payment:750} , {uptomonth:300,payment:500} ] 

对我来说最困难的是按"uptommonth"分组(因为这个值有重复),并获得每个"uptommonth"的总付款…

你知道怎么做吗?非常感谢!

试试这个

var data = [[ {uptomonth:84 , payment:150} ],[ {uptomonth:120 , payment:200} ],[ {uptomonth:120 , payment:100} , {uptomonth:180 , payment:250} , {uptomonth:300 , payment:500} ] ];
var newData = {};
data.forEach(function(array)
         { array.forEach(function(node)
                     {
                         if(!newData[node.uptomonth]){newData[node.uptomonth]=0};
                         newData[node.uptomonth] += node.payment;
                     });
         });
var ans = [];
Object.keys(newData).forEach(function(key){
    var abc = {};
    abc.uptomonth = key;
    abc.payment=newData[key];
    ans.push(abc);
});
ans.sort(function(a,b){return parseInt(a.uptomonth)>parseInt(b.uptomonth)});

变量ans是您想要的数组。

我建议您使用lodash中的_.flatten方法。

var data = [[ {uptomonth:84 , payment:150} ], 
            [ {uptomonth:120 , payment:200} ] ,
            [ {uptomonth:120 , payment:100} , 
              {uptomonth:180 , payment:250} , 
              {uptomonth:300 , payment:500} ]]
_
 .chain(data)
 .flatten()
 .reduce((acc, obj) => {
   var month = obj.uptomonth
   var payment = obj.payment
   if (acc[month]) acc[month] += payment
   else acc[month] = payment
   return acc
 }, {})
 .value()

您可以这样做:

  1. 将数组扁平化为只有
  2. 对象的数组
  3. 对新数组进行排序
  4. 计算付款总额
  5. 按月分组,计算每月付款

var data = [[ {uptomonth:84 , payment:150} ],[ {uptomonth:120 , payment:200} ],[ {uptomonth:120 , payment:100} , {uptomonth:180 , payment:250} , {uptomonth:300 , payment:500} ] ];
var finalResult = [];
//Flatten the array
var newArray = data.reduce(function(r, a) {
  a.forEach(function(o) {r.push(o)});
  return r;
}, [])
//Sort the array
newArray.sort(function(a, b) {
  return a.uptomonth - b.uptomonth;
});
//Get total payment
var total = newArray.reduce(function(r, a) {
  return r = r + a.payment;
}, 0)
//Group by uptomonth and calculate payment for each one
newArray.forEach(function(o) {
  if (!this.payment) this.payment = total;
  if (!this[o.uptomonth]) {
    this[o.uptomonth] = {uptomonth: o.uptomonth, payment: this.payment}
    finalResult.push(this[o.uptomonth]);
  }
  this.payment -= o.payment;
}, {});
console.log(finalResult)