這個怎麼樣(原生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