这个怎么样(原生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;
}
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]]
或类似这样的,与真正伟大的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]]
由于怀疑,“奇特”的实现比本地实现慢了一个数量级:jsperf comparison。
谢谢! - 曼JS从不直接... – Chrugel 2013-02-13 08:43:37
一些改进: - 我认为,如果测试:index.hasOwnProperty(i)是无用户。 - 我认为parseInt是无用的,因为my_array有数字。 - 要测试是否为0,请使用?代替。 ocurr == 0?0:总和/发生。 – 2013-02-13 08:46:02
只是为了澄清:谢谢大家!我简单地选择了这个答案,它给了我“开箱即用”的正确/预期结果。有了robertklep&Adrian Maire的(非常优雅的)解决方案,我最终在我的'label'子阵列中得到了字符串,这不是问题,但Tomalak提供了一个合适的解决方案。 – Chrugel 2013-02-13 08:57:36