Skip to content
Advertisement

JavaScript counting the chars from one string but not a different string ones?

I am working on a function which is supposed to take a string as a parameter and return it as an object literal where the keys are each letter of the string and the values would be the number of times that letter appears in the string (Excluding whitespaces).

I have come up with a code that seems to work, however, it only seems to work on the first string I pass but not in the second one. I have provided two strings and their expected outcome in the below code:

function frecuencias(str) {
  var freq = {};
  str = str.replace(/s/g, "").split("");
  for (let i = 0; i < str.length; i++) {
    freq[str[i]] = 0;

    for (let j in freq) {
      if (freq[str[i]] == freq[j]) {
        freq[str[i]] += 1;
      };
    };
  };
  return freq;
};

console.log(frecuencias("hola mundo"));
// { h: 1, o: 2, l: 1, a: 1, m: 1, u: 1, n: 1, d: 1 }

console.log(frecuencias("anita lava la tina"));
// { a: 6, n: 2, i: 2, t: 2, l: 2, v: 1 }

If you run that code, you will see that the count is correct for the first string, however, for the second one it doesn’t count appropriately.

Advertisement

Answer

Whenever you hit a letter, you initialize the the value to 0, even if the letter existed before:

freq[str[i]] = 0;

The inner loop is redundant. Just initialize/increment the current letter whenever you encounter it.

freq[str[i]] = // set the current letter in the freq object
  (freq[str[i]] || 0) // take the current value or 0 if it doesn't exist
   + 1; // add 1 to the current value

function frecuencias(str) {
  var freq = {};
  str = str.replace(/s/g, "").split("");
  for (let i = 0; i < str.length; i++) {
    // increment the current letter using 0 if letter doesn't exist on freq
    freq[str[i]] = (freq[str[i]] || 0) + 1;
  };
  return freq;
};

console.log(frecuencias("hola mundo"));
// { h: 1, o: 2, l: 1, a: 1, m: 1, u: 1, n: 1, d: 1 }

console.log(frecuencias("anita lava la tina"));
// { a: 6, n: 2, i: 2, t: 2, l: 2, v: 1 }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement