遍历包含三个键值对的对象数组

looping through an array of objects that contains three key, value pairs

我有这些对象,它们可以在一个数组中,就像在示例或数据库中一样:

[  
  { "payer": "DANNON", "points": 1000, "timestamp": "2020-11-02T14:00:00Z" }
  { "payer": "UNILEVER", "points": 200, "timestamp": "2020-10-31T11:00:00Z" } 
  { "payer": "DANNON", "points": -200, "timestamp": "2020-10-31T15:00:00Z" } 
  { "payer": "MILLER COORS", "points": 10000, "timestamp": "2020-11-01T14:00:00Z" } 
  { "payer": "DANNON", "points": 300, "timestamp": "2020-10-31T10:00:00Z" }
]

我想从这些对象的点值中减去总计 { "points": 5000 } 作为示例,从基于时间戳的最旧点开始,请记住付款人的点数不会变为负值。然后我想return 每个付款人的积分被使用了多少。预期结果如下所示:

[
  { "payer": "DANNON", "points": -100 },
  { "payer": "UNILEVER", "points": -200 },
  { "payer": "MILLER COORS", "points": -4,700 }
]

我最初的解决方案是:

  1. 根据最早的时间戳对数组进行排序
  2. 创建一个新对象来存储每个付款人使用的积分数
  3. 遍历排序数组并从每个付款人中减去积分,然后 存储在该新对象中使用的点数。
  4. 将所有新对象推送到一个数组并 return 它。 这个解决方案对我来说很有意义,但我无法实施,我一直有意想不到的结果,直到我的大脑冻结,我无法再思考了。

这是一道学徒面试题。一开始我认为这很容易,但后来花了几个小时没有解决它,我在想我是冒名顶替者吗?还是这个问题比较棘手?

感谢您分享您的知识和经验并帮助我。我很感激!

我刚刚实施了您在问题中列出的那些步骤并创建了一个函数 subtract(payers, subtractingPoints):

给定一个付款人数组和一些要减去的点,它将按时间戳对数组进行排序,并从每个付款人那里拿走这些点,直到达到该数字或在所有点之前达到数组长度可以减去。

函数 returns 一个对象数组,每个对象表示每个付款人(分组)获得了多少积分。

let payers = [  
  {
    "payer": "DANNON",
    "points": 1000,
    "timestamp": "2020-11-02T14:00:00Z"
  },
  {
    "payer": "UNILEVER",
    "points": 200,
    "timestamp": "2020-10-31T11:00:00Z"
  },
  {
    "payer": "DANNON",
    "points": -200,
    "timestamp": "2020-10-31T15:00:00Z"
  }, 
  {
    "payer": "MILLER COORS",
    "points": 10000,
    "timestamp": "2020-11-01T14:00:00Z"
  }, 
  {
    "payer": "DANNON",
    "points": 300,
    "timestamp": "2020-10-31T10:00:00Z"
  }
];

const o = subtract(payers, 5000);
console.log(o);

function subtract(payers, subtractingPoints){

  payers.sort(function(x, y){
    date1 = new Date(x.timestamp);
    date2 = new Date(y.timestamp);
    return date1 - date2 ;
  });
  
  payersAccounted = {};
  let i = 0;
  while(subtractingPoints > 0 && i < payers.length){
    
    const currentPayer = payers[i].payer;
    
    let pointsTookAway =
      Math.min(payers[i].points, subtractingPoints);
    
    if( !(currentPayer in payersAccounted) )
      payersAccounted[currentPayer] = pointsTookAway;
    else
      payersAccounted[currentPayer] += pointsTookAway;
      
    subtractingPoints -= pointsTookAway;
    i++;
  }
  
  let result = [];
  for (const [key, value] of Object.entries(payersAccounted)) {
    result.push( { "payer": key, "points": -1*value } );
  }
  
  return result;
}