Imagine we have an array filled with objects, where each object contains 3 key-value pairs.
const array = [ // overall frequency/occurrence
{ id: 1, value_1: 2, value_2: 3 }, // 3 times value 3
{ id: 2, value_1: 3, value_2: 4 }, // 1 time value 4
{ id: 3, value_1: 4, value_2: 3 }, // 3 times value 3
{ id: 4, value_1: 5, value_2: 2 }, // 2 times value 2
{ id: 5, value_1: 6, value_2: 3 }, // 3 times value 3
{ id: 6, value_1: 7, value_2: 2 }, // 2 times value 2
];
The task at hand is determining the current frequency count of each identical value_2
value within the entire array.
However, unlike the comments in the code snippet above, we need the output as an array where each element includes the current frequency count of its value_2
value, stored in an additional value_3
property ...
const array = [ // expected:
{ id: 1, value_1: 2, value_2: 3 }, // value_3: 1 (1st occurrence of 3)
{ id: 2, value_1: 3, value_2: 4 }, // value_3: 1 (1st occurrence of 4)
{ id: 3, value_1: 4, value_2: 3 }, // value_3: 2 (2nd occurrence of 3)
{ id: 4, value_1: 5, value_2: 2 }, // value_3: 1 (1st occurrence of 2)
{ id: 5, value_1: 6, value_2: 3 }, // value_3: 3 (3rd occurrence of 3)
{ id: 6, value_1: 7, value_2: 2 }, // value_3: 2 (2nd occurrence of 2)
];
I managed to add value_3
as a new key in each object, but I'm struggling to iterate through the array to determine the current frequency count of value_2
for each item.