Codility lessons #2

Wojciech Trawiński
JavaScript everyday
2 min readJan 13, 2019

Odd Occurrences In Array

It’s the second day with Codility lessons 🤩. Today I will focus on determining an items which doesn’t have a corresponding element with the same value in a given array. Let’s get down to looking for a black sheep 🐑.

Task description

The goal is to write a function which accepts an array of integers with odd number of elements. Each item present in the array can be paired with an element with the same value, except for the one unpaired item (a.k.a. black sheep 🐑) which the function has to return.

Of course the in-depth task’s description can be found here.

Solution

The task required making a map/dictionary with keys equal to integers present in the considered array. The map stored occurrences count of each integer in the collection.

Since the aim was to create a map/dictionary out of a given array, the reduce method of an Array instance was a perfect choice.

The accumulator function (makeIntegerOccurrencesMap) had to increase the occurrences count for a given key (integer) each time it was encountered in the array. In addition, the function had to initialize the occurrences count for the first integer’s occurrence.

Having integerOccurrencesMap, I had to find the key in the map with the corresponding value being an odd number.

Since I was interested in the map’s key, I made use of Object.keys static method to retrieve an array of the map’s keys. Next, I used the find method to return the key which corresponding value in the map was an odd number.

Finally, the key which was a string had to be converted to a number with the aid of ‘+’ operator.

Conclusions

In order to solve the tasks, it was necessary to create the integerOccurrencesMap and further find the key for which a value was an odd number. In addition, I had to cast the key to a number, since an object’s key is always a string. Using ‘+’ operator is a nifty way to convert a string to a number.

--

--