Exercise 4: MaxChars

Directions

Given a string, return the character that is most commonly used in the string.

Examples

maxChar("abcccccccd") === "c"
maxChar("apple 1231111") === "1"

Guidelines

Two ways to Convert string into a character map (an object)

CharMap

  1. Split the string into array and then use a forEach helper to loop over all the characters
  2. Use the for...of loop to loop over all the characters for...of loop is used on array or string (iterable object) for...in loop is used on an actual object

Solution:

obj[char]: return a reference to that particular character or at least its value

In [5]:
function maxChar(str){
  const obj = {};
  for (let char of str){
    if (!obj[char]){
      obj[char] = 1;
    } else {
      obj[char]++;
   }
  }    
}

Alternative Solution

In [6]:
function maxChar(str) {
  const charMap = {};
  let max = 0;
  let maxChar = "";

  // Build a character map
  for (let char of str){
    charMap[char] = charMap[char] + 1 || 1; // use boolean instead of if
  }

  // loop through an object
  for (let key in charMap){
    if (charMap[key] > max){
      max = charMap[key];
      maxChar = key;
    }
  }

  return maxChar;
}
In [7]:
maxChar("abcccccccd")
Out[7]:
'c'
In [8]:
maxChar("apple 1231111")
Out[8]:
'1'