Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

86
Views
JavaScript function to get the number of occurrences of each letter in specified string

I am new to JavaScript. Can anyone tell me why counter = 1 is added in following code ?

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");
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!