これはどのように(ネイティブ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 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]]
として:本当に偉大linq.js(私が使用したV2.2)と
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]]
またはこのような
、疑わしいことに、 "派手な"実装はネイティブの実装よりも遅いオーダーです:
jsperf comparison。
ありがとうございます! - 男のJSは決してまっすぐ進むことはありません... – Chrugel
いくつかの改善点: - 私はifテスト:index.hasOwnProperty(i)はユーザーがいないと思う。 - my_arrayに数字があるので、parseIntは役に立たないと思います。 - 発生するかどうかをテストするには、0ですか?代わりに。 ocurr == 0?0:sum/occur。 –
明確にする:ありがとうございました!私は単純にこの答えを選んだ。それは正しい/期待された結果を「すぐに」提供する。 robertklepとAdrian Maireの(非常にエレガントな)ソリューションで、私は問題ではない私の 'label'-subarrayの文字列で終わるが、Tomalakは適切な解決法を提供した。 – Chrugel