Get Number Frequency

EasyUiPath

Prompt

Write a function named getNumberFrequency in JavaScript that takes an array of numbers as an argument and returns an object containing the frequency count of each number in the array.

Requirements

  • The function should count the occurrences of each number in the input array.
  • The output should be an object where the keys are the numbers and the values are their frequencies.
  • The function should handle nested arrays.

Example

let SAMPLE_DATA = [
[1, 2, 3, 2],
[2, 5, 1, 7, 1],
[3, 4, 2, 5, 2, 8]
];

getNumberFrequency(SAMPLE_DATA);
/* Output:
{
'1': 3,
'2': 5,
'3': 2,
'4': 1,
'5': 2,
'7': 1,
'8': 1
}
*/

getNumberFrequency([1, 2, 3, 1, 2, 1]);
/* Output:
{
'1': 3,
'2': 2,
'3': 1
}
*/

Playground

Hint 1

First, you'll need to flatten the array if it contains nested arrays. Then, you can iterate through the flattened array and use an object to keep track of the frequency of each number. You could also use a nested loop to count the frequency of each number.

Solution

Explanation

This problem asks us to count the frequency of each number in an array, which may contain nested arrays. Let's break down the solution. ✨

First, we flatten the input array using the native javascript flat() method.

const flatArray = arr.flat();

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth (default is 1, which is sufficient for our case). The beauty of this approach is that it works seamlessly for both nested and non-nested arrays without requiring any conditional checks, if there are no nested arrays, it simply returns a shallow copy of the original array.

Next, we initialize an empty object to store the frequency of each number.

const frequencyMap = {};

Then, we iterate through the flattened array and count the occurrences of each number.

for (const num of flatArray) {
frequencyMap[num] = (frequencyMap[num] || 0) + 1;
}

This line is doing something clever. For each number in the array.

  • If the number already exists as a key in our frequency map, we get its current count (otherwise it's 0)
  • We add 1 to this count
  • We assign this new count back to the frequency map for this number

Finally, we return the frequency map, which now contains the count of each number.

return frequencyMap;

The time complexity of this solution is O(n), where n is the total number of elements in the input array (including nested elements), as we need to process each element once.

An alternative approach could use the reduce() method to build the frequency map in a more functional programming style.

const getNumberFrequency = (arr) => {
const flatArray = arr.flat();

return flatArray.reduce((acc, num) => {
acc[num] = (acc[num] || 0) + 1;
return acc;
}, {});
};

Both approaches are valid and have the same time complexity, so the choice between them is a matter of personal preference or coding style.

00:00