@@ -128,32 +128,41 @@ Let's break down this example step by step:
128
128
129
129
<div className = " my-4" >
130
130
131
- 1 . First, we start with an array of numbers that has some duplicates:
131
+ 1 . We start with an array of numbers that contains some duplicates:
132
132
<CodeSnippet language = " javascript" content = { ` const numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5]; ` } />
133
133
134
- 2 . We use reduce with an empty object ` {} ` as the initial value :
134
+ 2 . We initialize reduce with an empty object as our accumulator :
135
135
<CodeSnippet language = " javascript" content = { ` const frequency = numbers.reduce((count, num) => {}, {}); ` } />
136
136
137
- 3 . For each number in the array, we:
138
- For each number in the array, we:
139
- - Check if the number exists as a key in our object using ` count[num] `
140
- - If it doesn't exist, use ` 0 ` as the default value with ` || 0 `
141
- - Add 1 to the count
142
- - Return the updated count object
143
-
144
- 4 . Let's see how the object changes in each iteration:
145
-
146
-
147
- 5 . The key part of this code is the line:
137
+ 3 . In each iteration, we:
138
+ - Use the current number as a key in our object (` count[num] ` )
139
+ - If this number hasn't been seen before, start its count at 0
140
+ - Add 1 to the count for this number
141
+ - Return the updated count object for the next iteration
142
+
143
+ 4 . Let's walk through how the object is built:
144
+ - Initial: ` {} `
145
+ - After 1: ` { 1: 1 } `
146
+ - After 2: ` { 1: 1, 2: 1 } `
147
+ - After 2: ` { 1: 1, 2: 2 } `
148
+ - After 3: ` { 1: 1, 2: 2, 3: 1 } `
149
+ - And so on...
150
+
151
+ 5 . The magic happens in this line:
148
152
<CodeSnippet language = " javascript" content = { ` count[num] = (count[num] || 0) + 1; ` } />
149
- This is a shorthand way of writing:
153
+
154
+ Which is a shorter way of writing:
150
155
<CodeSnippet language = " javascript" content = { ` if (count[num] === undefined) {
151
156
count[num] = 1;
152
157
} else {
153
158
count[num] = count[num] + 1;
154
159
} ` } />
155
160
156
- This pattern is commonly used when you need to count occurrences in an array or create frequency maps, such as in analytics, data processing, or character frequency counting in strings.
161
+ This technique is incredibly useful when you need to count occurrences in data. You might use it to:
162
+ - Track user interactions in analytics
163
+ - Count character frequencies in strings
164
+ - Analyze voting or survey results
165
+ - Generate statistics from data sets
157
166
</div >
158
167
159
168
0 commit comments