Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple of letters count in js

i have a task:
Count the number of letters “a” in text
Count the number of letters “o” in text
Write the result of multiplying the number of letters “a” and “o”.

is it possible to solve this task in a shorter way??

function countString(str, letter) {
  let count = 0;
  for (let i = 0; i < str.length; i++) {
    if (str.charAt(i) == letter) {
      count += 1;
    }
  }
  return count;
}

const string = hello my name is Ola.toLowerCase()
const letterToCheck = "o"
const letterToCheckTwo = "a"

const result = countString(string, letterToCheck);
const resultTwo = countString(string, letterToCheckTwo);


const total = result + resultTwo
console.log(total)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can create an object that stores the count of all the characters and then you can compute the product using this object.

const str = "Avacado";
const charsCount = Array.prototype.reduce.call(
  str,
  (r, ch) => {
    const lowerCh = ch.toLowerCase()
    r[lowerCh] ??= r[lowerCh] || 0;
    r[lowerCh] += 1;
    return r;
  },
  {}
);

console.log(charsCount["o"] * charsCount["a"]);

Note: Array.prototype.reduce is a generic method, so it can be used with a string as well.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading