1
+ // Step By Step
2
+ function MeanMode ( arr ) {
3
+ // First, we declare an empty object to hold the number of times each item in the input array occurs,
4
+ var modeMap = { } ;
5
+ // a variable to hold the actual mode,
6
+ var mode = 0 ;
7
+ // a variable to hold the number of times the mode occurs,
8
+ var modeCount = 0 ;
9
+ // and a variable to hold the sum of the items in the array (to calculate the mean),
10
+ var sum = 0 ;
11
+
12
+ // Next, we loop through each item in the input array and...
13
+ for ( var i = 0 ; i < arr . length ; i ++ ) {
14
+ // ...add each value to our sum variable
15
+ sum += arr [ i ] ;
16
+
17
+ // ...check if each value is present in our frequency count
18
+ if ( modeMap [ arr [ i ] ] ) {
19
+ // If it is, we increase its value by 1.
20
+ modeMap [ arr [ i ] ] ++ ;
21
+ } else {
22
+ // If it isn't, we initialize its value to 1.
23
+ modeMap [ arr [ i ] ] = 1 ;
24
+ }
25
+
26
+ // ...and check if the count is greater than our current mode's count.
27
+ if ( modeMap [ arr [ i ] ] > modeCount ) {
28
+ // If it is, we set the mode to the current item in our input array...
29
+ mode = arr [ i ] ;
30
+ // ...and set the number of times the mode has occured to the current item's value in our mode array.
31
+ modeCount = modeMap [ arr [ i ] ] ;
32
+ }
33
+ }
34
+
35
+ // Next, we calculate the mean by dividing the sum by the total number of items in the array.
36
+ var mean = sum / arr . length ;
37
+
38
+ // If the mean and the mode are the same, we return 1, otherwise we return 0.
39
+ if ( mean === mode ) {
40
+ return 1 ;
41
+ } else {
42
+ return 0 ;
43
+ }
44
+ }
45
+
46
+ // Without Comments
47
+ function MeanMode ( arr ) {
48
+ var modeMap = { } ;
49
+ var mode = 0 ;
50
+ var modeCount = 0 ;
51
+ var sum = 0 ;
52
+
53
+ for ( var i = 0 ; i < arr . length ; i ++ ) {
54
+ sum += arr [ i ] ;
55
+
56
+ if ( modeMap [ arr [ i ] ] ) {
57
+ modeMap [ arr [ i ] ] ++ ;
58
+ } else {
59
+ modeMap [ arr [ i ] ] = 1 ;
60
+ }
61
+ if ( modeMap [ arr [ i ] ] > modeCount ) {
62
+ mode = arr [ i ] ;
63
+ modeCount = modeMap [ arr [ i ] ] ;
64
+ }
65
+ }
66
+
67
+ var mean = sum / arr . length ;
68
+
69
+ if ( mean === mode ) {
70
+ return 1 ;
71
+ } else {
72
+ return 0 ;
73
+ }
74
+ }
0 commit comments