【问题标题】:Calculate average among JSON objects计算 JSON 对象之间的平均值
【发布时间】:2017-12-01 01:27:54
【问题描述】:

我需要计算一个 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)

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

我很欣赏包含 Lodash 等库的解决方案

【问题讨论】:

标签: javascript json node.js algorithm


【解决方案1】:

说明

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

代码

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);
&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"&gt;&lt;/script&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 2018-02-10
    • 2017-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多