JS计算2d数组中相同元素的平均值

Chr*_*gel 5 javascript

我有一个由两列表示为数组的"表".第一列是1到20的数字,它们是标签,第二列是相应的值(秒):

my_array = [ [ 3,4,5,3,4,5,2 ],[ 12,14,16,11,12,10,20 ] ];
Run Code Online (Sandbox Code Playgroud)

我需要每个标签的平均值(平均值):

my_mean_array = [ [ 2,3,4,5 ],[ 20/1, (12+11)/2, (14+12)/2, (16+10)/2 ] ];
// edit: The mean should be a float - the notion above is just for clarification.
// Also the number 'labels' should remain as numbers/integers.
Run Code Online (Sandbox Code Playgroud)

我的尝试:

var a = my_array[0];
var b = my_array[1];
m = [];
n = [];
for( var i = 0; a.length; i++){
    m[ a[i] ] += b[i]; // accumulate the values in the corresponding place
    n[ a[i] ] += 1; // count the occurences
}
var o = [];
var p = [];
o = m / n;
p.push(n);
p.push(o);
Run Code Online (Sandbox Code Playgroud)

Tom*_*lak 3

怎么样(原生 JS,不会在旧浏览器上崩溃):

function arrayMean(ary) {
  var index = {}, i, label, value, result = [[],[]];

  for (i = 0; i < ary[0].length; i++) {
    label = ary[0][i];
    value = ary[1][i];
    if (!(label in index)) {
      index[label] = {sum: 0, occur: 0};
    }
    index[label].sum += value;
    index[label].occur++;
  }
  for (i in index) {
    if (index.hasOwnProperty(i)) {
      result[0].push(parseInt(i, 10));
      result[1].push(index[i].occur > 0 ? index[i].sum / index[i].occur : 0);
    }
  }
  return result;
}
Run Code Online (Sandbox Code Playgroud)

FWIW,如果你想要奇特,我已经创建了一些其他方法来做到这一点。它们依赖于外部库,并且很可能比本机解决方案慢一个数量级。但它们看起来更好看。

它可能看起来像这样,带有underscore.js

function arrayMeanUnderscore(ary) {
  return _.chain(ary[0])
    .zip(ary[1])
    .groupBy(function (item) { return item[0]; })
    .reduce(function(memo, items) {
      var values = _.pluck(items, 1),
          toSum = function (a, b) { return a + b; };

      memo[0].push(items[0][0]);
      memo[1].push(_(values).reduce(toSum) / values.length);
      return memo;
    }, [[], []])
    .value();
}

// --------------------------------------------

arrayMeanUnderscore([[3,4,5,3,4,5,2], [12,14,16,11,12,10,20]]);
// -> [[2,3,4,5], [20,11.5,13,13]]
Run Code Online (Sandbox Code Playgroud)

或者像这样,使用真正出色的linq.js(我使用过 v2.2):

function arrayMeanLinq(ary) {
  return Enumerable.From(ary[0])
    .Zip(ary[1], "[$, $$]")
    .GroupBy("$[0]")
    .Aggregate([[],[]], function (result, item) {
      result[0].push(item.Key());
      result[1].push(item.Average("$[1]"));
      return result;
    });
}

// --------------------------------------------

arrayMeanLinq([[3,4,5,3,4,5,2], [12,14,16,11,12,10,20]]);
// -> [[3,4,5,2], [11.5,13,13,20]]
Run Code Online (Sandbox Code Playgroud)

正如所怀疑的,“花哨”的实现比本机实现慢一个数量级:jsperf Comparison

  • @AdrianMaire 在使用“for ... in”遍历对象时,“hasOwnProperty”永远不会无用。需要“parseInt”,因为 Tomalak 使用对象(“index”)来存储事件映射。如果没有“parseInt”,“i”将是一个字符串。 (2认同)