Function That Receives An Array Of Strings & Outputs Most Used String


I love the occasional programming challenge and yesterday I came across the following:

Create a function that receives an array of strings and outputs the most used string?

I pondered on this for awhile and in my mind thought of the following process:

  1. Loop through each element of the original array;
  2. Count the occurrences of each element by looping through the array again;
  3. Sort the new array;
  4. Output the new array’s first element.

However, looking at this I realised I was looping way too many times!

So I refactored my code such that it does the following:

function getModal( arr ) {
  var maxCount = 0;
  var result = "";
  arr.reduce( function( p, el ) {
    p[el] ? p[el] += 1 : p[el] = 1;
    if ( p[el] > maxCount ) {
      maxCount = p[el];
      result = el;
    } 
    return p;
  }, {} );
  return result;
}

var e = ["h","g","x", "d", "b", "h", "x", "i", "s", "g", "x", "p"];

console.log( getModal( e ) ); // => "x"

Notice how there’s only one looping array function used – reduce.

What this function does is take the array arr as a parameter, create two variables to measure the maxCount and another to take the result. As we then loop through the arr we assign each element (being a string) as a key to the new object created by reduce and make it’s property value equal to the count.

This makes counting the number of occurrences relatively easy.

All we then do is check whether the property value is greater than the maxCount value and if it is to make that value equal to the maxCount and the result equal to that element.

Once we’ve finished looping through the arr we then just simply output the result.

If we need to output the count of occurrences we could just change our code to output:

return {
    answer : result,
    count : maxCount
};

Anyway, I’m sure there is a better answer to my response, but I liked the challenge and I also liked the refactoring process – looking at my code and finding a better way.

Recent Posts