Counting Frequency

One essential algorithm tool to have under your belt is where you identify the number of times a data point presents itself in some amount of data. This could be an array, or a string, or a complex Json tree you need to dig down into. If data comes into your function and you need to know how frequently each piece of data is repeated, this is the blog for you.

I’m doing this one in JavaScript because I love JavaScript, but you can do it in most languages that have loops and objects/sets/hashes.

let data1 = 'This is a fairly short string.'
let data2 = [ 1,2,3,4,2,4,2,3,4,5,2,5,1,3 ]
function dataToFrequency(data){
let frequency = {}
for(let i = 0; i < data.length; i++){
frequency[data[i]]
? frequency[data[i]] += 1
: frequency[data[i]] = 1
}
return frequency
}

This little bit of code will return an object where each key is the entering data point, and each value is the number of times the data point repeats itself. Let’s break it down.

This code assumes its only job is to transform “clean” data into a frequency object. It’s a principle of functional programming that each function is performing it’s one function. This dataToFrequency function shouldn’t be identifying the type of data and cleaning it, that should be a different functions job. So if there’s a type error that shows up here, we can go upstream of this function to find out why the data wasn’t clean. Below I’ll give an example of a less adaptable code that requires more operations to do the same job.

As soon as the data comes into the function it’s immediately declaring the answer container. Next it’s going over a standard for loop. There are definitely some things to pay attention to here. The data coming into the function has to be iterable or the function will break. Then the data hits a ternary statement; which, evaluates whether or not our answer container has a matching key. If it does it increments the value one. If not it instantiates that key with an initial value of one.

Repeat until finished. Then return that result to the next function. Please note on it’s own this function will handle data1 or data2.

Liked this one? Read more about the problems this solution avoided and an intro to functional programming here.

A software engineer living in lonely world! He took the midnight train going anywhere.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store