计算JSON对象的平均值

时间:2017-11-30 16:42:21

标签: javascript json node.js algorithm

我需要计算json数组的所有属性的平均值。 这是我提出的解决方案,它有效,但我认为有更优雅的方法来达到相同的结果。



const measures = ['g1','g2','g3'];
const res = [{g1: 1, g2: 3, g3: 5}, {g1: 2, g2: 4, g3: 6}, {g1: 3, g2: 5, g3: 7}]
const data = { g1: 0, g2: 0, g3: 0 };
for (let i = 0; i < measures.length; i += 1) {
  for (let j = 0; j < res.length; j += 1) {
    data[measures[i]] += res[j][measures[i]];
  }
  data[measures[i]] /= res.length;
}
console.log(data)
&#13;
&#13;
&#13;

可运行的例子: https://repl.it/repls/SilverFlippantKiwi

我很欣赏包含一些像Lodash

这样的库的解决方案

1 个答案:

答案 0 :(得分:-1)

解释

  1. 将您的数据转换为{key: [value1, value2, ...], key2: [values]}
  2. 然后将此对象的值转换为平均值
  3. 代码

    const measures = ['g1', 'g2', 'g3'];
    const res = [{
      g1: 1,
      g2: 3,
      g3: 5
    }, {
      g1: 2,
      g2: 4,
      g3: 6
    }, {
      g1: 3,
      g2: 5,
      g3: 7
    }]
    
    let a = 
    _.mapValues(                    // convert the list of numbers to the mean (step 2)
        _.mergeWith(                // group the values by key (step 1)
                    {},                 // start with an empty object
                    ...res,             // pass each element in your original array (res) as an argument
                    (objValue, srcValue) => // add each element with the right key to an array for that key
                      _.isArray(objValue) ? objValue.concat(srcValue) : [srcValue]),
        _.mean);
    
     console.log(a);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>