Counting the number of times each value in an array appears in that array (javascript)

I have a question about how I need to do some math on an array. My apologies if this is the main question, javascript is not my strongest language, and I am a very mediocre programmer in the best days.

I have an array of values โ€‹โ€‹and as part of the analysis, I run the mann-kendall test, but I hit the wall where I calculate the variance. ( http://vsp.pnnl.gov/help/Vsample/Design_Trend_Mann_Kendall.htm Step # 6)

Essentially, I would like to count the number of times each value in an array appears in this array. So, for example, in a specific pixel of the world, an array may look like this:

[1, 1, 0.7, 0.3, 1, 0.8, 1, 0.8, 0.7, 1] 

I need to count the number of times a certain value appears, then run the expression Expression (value * (value-1) * (value * 2 + 5));

So, for this array, I want different values โ€‹โ€‹to be taken into account ...

 1: 5 0.7: 2 0.8: 2 0.3: 1 

And then calculate the meaning of these โ€œconnectionsโ€ as 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) 

A few notes:

  • This is Javascript for maps (I think the google map engine), so some of the more standard Javascript answers may not work (I already tried several script options from other SO streams ( Counting the values โ€‹โ€‹of the elements of the Javascript array .)
  • These arrays are unique for every pixel across the planet, so I think the best way to do this would be as a function.
  • As you can see above, the values โ€‹โ€‹with the number 1 drop out, which is good, but I need to avoid double counting elements to just convert the array to counts ( [5, 5, 2, 1, 5, 2, 5, 2, 2, 5] ) equals false.
  • I am limited to the standard Javascript library.
-1
source share
2 answers

 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; } 
+1
source
 function foo(arr) { var a = [], b = [], prev; arr.sort(); for( var i = 0; i < arr.length; i++ ){ if ( arr[i] !== prev ) { a.push(arr[i]); b.push(1); } else { b[b.length-1]++; } prev = arr[i]; } return [a, b]; } var arr = [1, 1, 0.7, 0.3, 1, 0.8, 1, 0.8, 0.7, 1]; var result = foo(arr); // result[0] contain unique array elements and result[1] contain number of occurrences of those elements for(var i = 0; i < result[0].length; i++){ document.write(result[0][i] + " : " + result[1][i] + "<br>"); } 
0
source

All Articles