Home > Back-end >  Multiple of letters count in js
Multiple of letters count in js

Time:06-21

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)

CodePudding user response:

With regular expression function match() will output all the matched conditions.

const string = "hello my name is Ola"
const numberOfA = string.match(/a/gi);
const numberOfO = string.match(/o/gi);
console.log(numberOfA.length * numberOfO.length)

CodePudding user response:

you can do something like this using map filter and reduce

const calculate = (string, letters) => letters
  .map(l => string.split('').filter(c => c === l).length)
  .reduce((res, item) => res * item)


const string = 'hello my name is Ola'.toLowerCase()

console.log(calculate(string, ['a', 'o']))
console.log(calculate(string, ['a', 'o', 'e']))

CodePudding user response:

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.

CodePudding user response:

There are a few different approaches. In this post I've programmed in a way that allows you to expand to different letters, different amounts of letters, and different strings easily. There may be better approaches if your problem never needs to change.

In your current code, your are traversing the strings twice and counting the occurrences of the letter within them. You could easily pass the function an array and only traverse the string once:

function countString(str, letters) {
  //rather than being a character, letter is now an array of characters
  let count = 0;
  for (let i = 0; i < str.length; i  ) {
    if (letters.includes(str.charAt(i))) {
      count  = 1;
    }
  }
  return count;
}

const string = "hello my name is "    Ola.toLowerCase()
const lettersToCheck = ["o", "a"]


const result = countString(string, lettersToCheck);

//iterate over the array to get the total
var product = 1;
for (int i = 0; i < result.length; i  ){
   product *= result[i];
}


console.log(product);

Rather than iterating over the strings, however, a different approach is to use regular expressions and .match(). This approach has fewer iterations, although I'm not sure about the low level efficiency, since lots of the comparison is encapsulated by .match():

function countString(str, letters) {
  //iterates over the array of letters rather than the string
  for (var i = 0; i < letters.length; i  ){
  count  = (str.match(new RegExp(letters[i], "g")) || []).length; 
  }
  return count;
}

const string = "hello my name is "    Ola.toLowerCase()
const lettersToCheck = ["o", "a"]


const result = countString(string, lettersToCheck);

//iterate over the array to get the total
var product = 1;
for (int i = 0; i < result.length; i  ){
   product *= result[i];
}

console.log(product);

If regex is too much, you could also use .split() to iterate over the characters rather than the string:

function countString(str, letters) {
  //iterates over the array of letters rather than the string
  for (var i = 0; i < letters.length; i  ){
  count  = str.split(letters[i]).length - 1;
  }
  return count;
}

const string = "hello my name is "    Ola.toLowerCase()
const lettersToCheck = ["o", "a"]


const result = countString(string, lettersToCheck);

//iterate over the array to get the total
var product = 1;
for (int i = 0; i < result.length; i  ){
   product *= result[i];
}

console.log(product);

See this post for more information

CodePudding user response:

You can compute the letter frequency each time the phrase changes and then request the product by specifying the letters in the frequency map.

const letterFrequencyMap = (str) =>
  str.toLowerCase().split('').reduce((acc, k) =>
    acc.set(k, (acc.get(k) ?? 0)   1), new Map);

const computeProduct = (freq, ...keys) =>
  keys.reduce((product, k) => product * (freq.get(k) ?? 1), 1);

// Main

const phrase = "It's about to be noon in a bit.";
const freq = letterFrequencyMap(phrase);

// a = 2; o = 4
console.log(computeProduct(freq, 'a', 'o')); // 8

  • Related