Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

completed_exercises/maxchar/index.js #18

Open
amcereijo opened this issue Feb 14, 2018 · 0 comments
Open

completed_exercises/maxchar/index.js #18

amcereijo opened this issue Feb 14, 2018 · 0 comments

Comments

@amcereijo
Copy link

The solution should not avoid the second loop?

function maxChar(str) {
  const charMap = {};
  let max = 0;
  let maxChar = '';

  for(let element of str) {
    charMap[element] = charMap[element] ? charMap[element] + 1 : 1;

    if(charMap[element] >  max) {
      max = charMap[element];
      maxChar = element
    }
  }

  return maxChar;
}

instead of

function maxChar(str) {
  const charMap = {};
  let max = 0;
  let maxChar = '';

  for (let char of str) {
    if (charMap[char]) {
      charMap[char]++;
    } else {
      charMap[char] = 1;
    }
  }

  for (let char in charMap) {
    if (charMap[char] > max) {
      max = charMap[char];
      maxChar = char;
    }
  }

  return maxChar;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant