CouchDB 如何计算不同类型单据的平均值

xzv2uavs  于 2022-12-09  发布在  CouchDB
关注(0)|答案(1)|浏览(164)

我有一份这样的文件

{
  type: 'vehicles',
  vin: 1234, 
  companyId: 123,
  _id: 321
}

{
  type: 'company',
  name: 'x company',
  _id: 123
}
{
  type: 'company',
  name: 'y company',
  _id: 333
}

我正在尝试设计map reduce函数来获取每个公司的平均车辆数(allVehicle / allCompany),我希望通过调用如下键来获取值

key: ["averageVehiclesPerCompany"]
qc6wkl3g

qc6wkl3g1#

以下是计算平均值的完美解决方案

function calcAverage(companies) {
    var totalVehicle = 0;
    Object.keys(companies).map(function(key, index) {
        var vehicle = 0;
        if (!!companies[key].vin) {
            vehicle = companies[key].vin;
        }
        totalVehicle += vehicle;
    });
    return parseFloat(totalVehicle / companies.length).toFixed(2);
}

相关问题