Here we have one example find the frequency of the similar numbers that occur in the array list.
const example = [1, 4, 5, 3, 3, 2, 4, 5, 5, 8, 10]; const obj = {}; for (let index = 0; index < example.length; index++) { const element = example[index]; obj[element] = (obj[element] || 0) + 1; } console.log("The Frequency of the numbers in array is: \n"); console.log(obj);
Output of the program is :
The Frequency of the numbers in array is: { '1': 1, '2': 1, '3': 2, '4': 2, '5': 3, '8': 1, '10': 1 }
1. Create an array called `example` with some numbers.
const example = [1, 4, 5, 3, 3, 2, 4, 5, 5, 8, 10];
2. Create an empty object called `obj` to store the counts of each element.
const obj = {};
3. Iterate over each element in the `example` array using a `for` loop.
for (let index = 0; index < example.length; index++) {
const element = example[index];
// ...
}
4. Inside the loop, access the current element and use it as a key in the `obj` object.
obj[element] = (obj[element] || 0) + 1;
- If the current element (`element`) is not yet a key in the `obj` object, `obj[element]` will be `undefined`, so `(obj[element] || 0)` will be evaluated as `0`.
- Then, `0 + 1` will be assigned to `obj[element]`, effectively initializing the count for that element as `1`.
- If the current element (`element`) is already a key in the `obj` object, `(obj[element] || 0)` will retrieve its current count.
- Then, the count is incremented by `1` by adding `1` to the current value.
5. After the loop finishes, the `obj` object will contain the counts of each element in the `example` array.
For example, using the `example` array from above, the resulting `obj` object would be:
{
1: 1,
4: 2,
5: 3,
3: 2,
2: 1,
8: 1,
10: 1
}
This code is a basic implementation of counting element occurrences using an object as a counter. It can be useful in various scenarios where you need to analyze the frequency or distribution of elements in an array.