计算数组中每个值在该数组中出现的次数(javascript) [英] Counting the number of times each value in the array appears in that array (javascript)
问题描述
我有一个问题,我应该如何对数组执行一些数学运算.如果这是一个基本问题,我很抱歉,javascript不是我最强的语言,并且在我最好的日子里,我是一名普通的程序员.
I've got a question as to how I should go about performing some math over an array. My apologies if this is a basic question, javascript is not my strongest language and I'm a mediocre programmer on my best days.
我有一个值数组,作为分析的一部分,我正在执行mann-kendall检验,但是我碰到了要计算方差的墙.( http://vsp.pnnl.gov/help/Vsample/Design_Trend_Mann_Kendall.htm步骤6)
I have an array of values and as part of an analysis, I'm performing a mann-kendall test, but I've hit a wall where I'm calculating the variance. (http://vsp.pnnl.gov/help/Vsample/Design_Trend_Mann_Kendall.htm Step #6)
基本上,我想计算数组中每个值出现在该数组中的次数.因此,例如在世界的特定像素处,数组可能看起来像:
Essentially, I'd like to count the number of times each value in the array appears in that array. So for instance at a particular pixel of the world, the array might look like:
[1, 1, 0.7, 0.3, 1, 0.8, 1, 0.8, 0.7, 1]
我需要计算一个特定值出现的次数,然后运行表达式
表达式(值*(值-1)*(值* 2 + 5));
I need to count the number of times a particular value appears, then run the expression
Expression(value*(value-1)*(value*2+5));
因此,对于该数组,我想要不同的值计数...
So for that array, I want the distinct value counts...
1: 5
0.7: 2
0.8: 2
0.3: 1
然后计算这些关系"的值作为表达式的一部分...
And then compute the value of those "ties" as a part of the expression...
5 * (5-1) * (5*2 -5) +
2 * (2-1) * (2*2 -5) +
2 * (2-1) * (2*2 -5) +
1 * (1-1) * (1*2 -5)
一些注意事项:
- 这是用于地图的Javascript(例如Google Map Engine),因此某些更标准的Javascript答案可能不起作用(我已经尝试了其他SO线程的一些脚本变体(推荐答案
var arr = [1, 1, 0.7, 0.3, 1, 0.8, 1, 0.8, 0.7, 1]; document.write(compute(arr)); function compute(arr){ freq = {}; for(var i=0; i<arr.length; i++){ freq[arr[i]] = (freq[arr[i]] || 0) + 1; } var sum = 0; for(var i in freq){ sum += freq[i]*(freq[i]-1)*(freq[i]*2-5); } return sum; }
这篇关于计算数组中每个值在该数组中出现的次数(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!