EasyUiPath

Get Number Frequency

Prompt

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

  • 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 (as strings) and the values are their frequencies.
  • The function should handle nested arrays (one level deep).

Playground

Hint 1

Start by flattening the array so you don't have to worry about nesting. JavaScript's Array.prototype.flat() method can do this in one call.

Hint 2

Once the array is flat, iterate through it and use an object as a map. For each number, check if it already exists as a key. If it does, increment the count. If not, initialize it to 1.

Hint 3

A common shorthand for the counting pattern is map[num] = (map[num] || 0) + 1. The || 0 handles the case where the key doesn't exist yet (which would be undefined).

Solution

Explanation

Frequency counting is one of the most fundamental patterns in programming interviews, and this variation adds a small twist by requiring you to handle nested arrays first.

The solution starts by flattening the input with arr.flat(). This built-in method creates a new array with all sub-array elements pulled up one level. It works seamlessly for both nested and flat inputs: if there's nothing to flatten, it just returns a shallow copy. This is a nice touch because it means you don't need a conditional check for whether the array is nested.

Once the array is flat, we create an empty object called frequencyMap and iterate through each number with a for...of loop. The line frequencyMap[num] = (frequencyMap[num] || 0) + 1 is doing the heavy lifting. When num hasn't been seen before, frequencyMap[num] is undefined, and undefined || 0 evaluates to 0. So the first occurrence gets initialized to 1. On subsequent encounters, the existing count gets incremented.

Note that the keys in the resulting object are strings, not numbers. That's just how JavaScript objects work: any key you set with bracket notation gets coerced to a string. So frequencyMap[5] creates the key '5'. This is expected behavior for this problem.

The time complexity is O(n), where n is the total number of elements across all sub-arrays, since both flattening and counting require one pass through the data.

If you prefer a more functional style, you could use reduce to build the frequency map in a single expression:

const getNumberFrequency = (arr) =>
arr.flat().reduce((acc, num) => {
acc[num] = (acc[num] || 0) + 1;
return acc;
}, {});

Both approaches are equally valid and have the same performance characteristics. The for...of version tends to be easier to read and debug, while the reduce version is more concise.