Frequency of characters in Order of Appearance in JavaScript

Last Updated : 25 Feb, 2026

Character frequency in order of appearance in JavaScript means counting how many times each character occurs while keeping their original sequence. It helps analyze string patterns and character distribution.

  • Counts occurrences of each character in a string.
  • Maintains the original order of appearance.
  • Usually implemented using objects or maps.
  • Useful in text analysis and string processing.
  • Good practice for JavaScript logic building.

[Method 1]: Using Object

Object in JavaScript allow storing key value pairs. So we use items as keys and their frequencies as values.

JavaScript
function freqCount(s) {
  const freq = {};
  for (let x of s) {
    freq[x] = (freq[x] || 0) + 1;
  }
  return freq;
}

// Example usage
console.log(freqCount("geeksforgeeks"));

[Method 2]: Using Map

JS Map also store key value pairs and works for data types other than string as well.

JavaScript
function freqCount(s) {
  const m = new Map();
  for (let x of s) {
    m.set(x, (m.get(x) || 0) + 1);
  }
  return m;
}

// Example usage
console.log(freqCount("geeksforgeeks"));

[Method 3]: Using Regular Expression

If our input string contains mixed characters and we wish to find frequencies of only alphabetic characters, we can use regular expressions.

JavaScript
function freqCount(s) {
  return (s.match(/[a-z]/gi) || []).reduce((freq, x) => {
    freq[x] = (freq[x] || 0) + 1;
    return freq;
  }, {});
}

// Example usage
console.log(freqCount("geeksforgeeks"));
Comment