Counting Frequency of Characters in a String Using JavaScript

Counting frequency of characters in a string using JavaScript

Here you go:

function getFrequency(string) {
var freq = {};
for (var i=0; i<string.length;i++) {
var character = string.charAt(i);
if (freq[character]) {
freq[character]++;
} else {
freq[character] = 1;
}
}

return freq;
};

Javascript counting the frequency letters of a string

Two problems

  • use an object

    var array_lengths = {}; // object
  • return that object without sorting and other stuff

    return array_lengths;

function charFreq( string ) {    var array_lengths = {}; // object
// compute frequencies of each value for(var i = 0; i < string.length; i++) { value = string[i]; if(value in array_lengths) { array_lengths[value]++; } else { array_lengths[value] = 1; } } return array_lengths;}
//OUTPUT:// if I had it right I should get "true" from every of the following values of the function but the point is that I'm getting all false...where's the error?
counter = charFreq("abbabcbdbabdbdbabababcbcbab");console.log(counter);console.log( counter['a'] === 7);console.log( counter.b === 14);console.log( counter['c'] === 3);

Count the number of occurrences of a character in a string in Javascript

I have updated this answer. I like the idea of using a match better, but it is slower:

console.log(("str1,str2,str3,str4".match(/,/g) || []).length); //logs 3

console.log(("str1,str2,str3,str4".match(new RegExp("str", "g")) || []).length); //logs 4

Count number of occurrences for each char in a string

This is nice and simple in JavaScript (or any other language that supports arbitrary key/value maps). And for key/value mapping, in JavaScript you have two options: objects and Map instances. In most cases where the keys are arbitrary as in this case, a Map is the better choice (more on MDN). Here's how that looks:

// The string
const str = "I want to count the number of occurrences of each char in this string";

// A map for the character=>count mappings
const counts = new Map();

// Loop through the string...
for (const ch of str) {
// Get the count for it, if we have one; we'll get `undefined` if we don't
// know this character yet. Using nullish coalescing (`??`), we can turn
// that `undefined` into a `0`. (In obsolete environments that don't
// support nullish coalescing, for this use case we could use the logical
// OR operator [`||`] instead to use `0` instead of any falsy value, since
// A) `undefined` is falsy, and B) None of the count values we're tracking
// will be falsy because they're all non-zero. For some other use cases,
// we'd need to use a conditional testing `undefined` explicitly.)
const count = counts.get(ch) ?? 0;

// Add one and store the result
counts.set(ch, count + 1);
}

// Show the counts
for (const [ch, count] of counts) {
console.log(`"${ch}" count: ${counts.get(ch)}`);
}
.as-console-wrapper {
max-height: 100% !important;
}

Counting the occurrences / frequency of array elements

const arr = [2, 2, 5, 2, 2, 2, 4, 5, 5, 9];

function foo (array) {
let a = [],
b = [],
arr = [...array], // clone array so we don't change the original when using .sort()
prev;

arr.sort();
for (let element of arr) {
if (element !== prev) {
a.push(element);
b.push(1);
}
else ++b[b.length - 1];
prev = element;
}

return [a, b];
}

const result = foo(arr);
console.log('[' + result[0] + ']','[' + result[1] + ']')
console.log(arr)


Related Topics



Leave a reply



Submit