Home > database >  JavaScript function to get the number of occurrences of each letter in specified string
JavaScript function to get the number of occurrences of each letter in specified string

Time:03-31



function count(string) {
  let string1 = string.split("").sort().join("");
  let counter = 1;
  for (let i = 0; i < string1.length; i  ) {
    if (string1[i] == string1[i   1]) {
      counter  ;
    } else {
      console.log(string1[i]   " "   counter);
      counter = 1;//-----------> this one
    }
  }
}
count("amanpreetsaingh");



hi, i am new to java script. can anyone tell me why counter = 1 is added in following code?

CodePudding user response:

You sort the whole characters in the string and start from left to right.

If your string is amanpreetsaingh, it becomes aaaeeghimnnprts.

Now what you do is keep a counter=1 starting from index 0. And check for every letter you check if it is equal to the next one, if yes then we are counting for the same letter and increase counter (like in case of the first two as). Once we reach the last a, our next letter (e) is not the same as our current letter, so we log our current value and reset count.

CodePudding user response:

you can simply use reduce function:

reduce it's an array method so make sure to transform your string into array by using split(""):

text.split("") // ["a", "a", "a", "a", "b", "b", "b", "c", "c", "c", "c", "c", "c", "c", "d", "d", "d", "d", "d", "d", "d"]

then apply reduce on the result array :

  text.split("").reduce((acc, c) => {
  const counter = acc[c] || 0;
  return {
    ...acc,
    [c]: counter   1,
  };
}, {}); // { a: 4, b: 3, c: 6, d: 5 }

I suggest you watch this series of videos about the arrays method from ack Herrington: https://youtu.be/NaJI7RkSPx8

  • Related