这个怎么样(原生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;
}
如果你想要花哨的效果,我已经创造了一些其他方法来实现它。它们依赖于外部库,并且很可能比本地解决方案慢一个数量级。但是它们看起来更加漂亮。
使用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]]);
或者像这样,使用真正伟大的 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]]);
怀疑的情况下,“高级”的实现比本地实现慢了一个数量级:
jsperf对比。
for ... in
遍历对象时,hasOwnProperty
是绝不无用的。由于 Tomalak 使用对象(index
)来存储出现次数的映射,因此需要使用parseInt
。如果没有parseInt
,i
将是一个字符串。 - Yoshi0
改为三元运算符,这样更清晰了。 - Tomalak