简体   繁体   English

使用对象键作为日期以获取平均值

[英]Use Object keys as dates to get average of values

I have an object like so. 我有这样的一个对象。 They key is a timestamp and the value is my number 他们的钥匙是一个时间戳记,值是我的电话号码

var history = {
     '1505845390000': 295426,
     '1505757979000': 4115911,
     '1505677767000': 4033384,
     '1505675472000': 4033384,
     '1505591090000': 3943956,
     '1505502071000': 3848963,
     '1505499910000': 3848963,
     '1505499894000': 3848963
}

What I want to do is: 我想做的是:

1) For the latest 5 dates (keys), get an average of the values 2) For a date range, get an average of the values 1)对于最近的5个日期(键),请获取平均值。2)对于日期范围,请获取其平均值。

you can do the following for the first case 您可以针对第一种情况执行以下操作

 var obj = { '1505845390000': 295426, '1505757979000': 4115911, '1505677767000': 4033384, '1505675472000': 4033384, '1505591090000': 3943956, '1505502071000': 3848963, '1505499910000': 3848963, '1505499894000': 3848963 } let ans = Object.keys(obj).sort(); ans = ans.slice(ans.length-5).reduce((a, b) => a+obj[b], 0); console.log(ans/5); 

For the 2nd case you can do 对于第二种情况,您可以

 var obj = { '1505845390000': 295426, '1505757979000': 4115911, '1505677767000': 4033384, '1505675472000': 4033384, '1505591090000': 3943956, '1505502071000': 3848963, '1505499910000': 3848963, '1505499894000': 3848963 } let start = '1505591090000', end = '1505845390000' let ans = Object.keys(obj).filter(e => e>=start && e<=end); let result = ans.reduce((a,b) => a+obj[b],0)/ans.length console.log(result); 

This answer has a good explanation of how to filter an object by its keys: 这个答案很好地解释了如何通过其键过滤对象:

https://stackoverflow.com/a/38750895/5009210 https://stackoverflow.com/a/38750895/5009210

Basically use Object.keys() to get an array of keys, then Array.filter() to select the ones you want, then Array.reduce() to reconstruct an object with the relevant values for the filtered keys. 基本上,使用Object.keys()获取一个键数组,然后使用Array.filter()选择所需的键,然后Array.filter() Array.reduce()重建具有过滤后键的相关值的对象。 Like this: 像这样:

Object.keys( history )
   .filter( someFilterFunction )
   .reduce( (obj, key) => {
      obj[key] = history[key];
   }, {});

Once you've done this, you can extract the remaining values using Object.values() and then pass them to a simple average function (I assume you want the mean average): 完成此操作后,您可以使用Object.values()提取剩余的值,然后将它们传递给一个简单的平均值函数(我假设您想要平均值):

function meanAverage( valuesToAverage ) {
    //avoid divide by zero
    if ( valuesToAverage.length ) {
       const valueSum = sum( valuesToAverage );
       return valueSum / valuesToAverage.length;
    }
    return 0;
}

function sum( valuesToSum ) {
   return valuesToSum.reduce( (a, b) => a + b );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM