大佬教程收集整理的这篇文章主要介绍了javascript – JS计算2d数组中相同元素的平均值,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要每个标签的平均值(平均值):
@H_330_2@my_mean_array = [ [ 2,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.我的尝试:
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);
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,如果你想要花哨我已经创造了一些其他方法来做到这一点.它们依赖于外部库,并且很可能比原生解决方案慢一个数量级.但他们看起来更好.
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,2],[12,20]]); // -> [[2,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,20]]); // -> [[3,[11.5,20]]
正如所怀疑的那样,“花哨”实现比本机实现慢一个数量级:jsperf comparison.
以上是大佬教程为你收集整理的javascript – JS计算2d数组中相同元素的平均值全部内容,希望文章能够帮你解决javascript – JS计算2d数组中相同元素的平均值所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。