So I am trying to map the number of times a char appears in a string. I know that in C++ it would be.
std::string str = "AbBAaaaa";
std::unordered_map<char, int> myMap;
for(auto i = str)
{
++mymap[i];
}
How would I translate this to JavaScript?
So I am trying to map the number of times a char appears in a string. I know that in C++ it would be.
std::string str = "AbBAaaaa";
std::unordered_map<char, int> myMap;
for(auto i = str)
{
++mymap[i];
}
How would I translate this to JavaScript?
Share Improve this question edited Aug 20, 2018 at 0:50 Tas 7,1114 gold badges39 silver badges54 bronze badges asked Aug 20, 2018 at 0:33 Tom OconnorTom Oconnor 4132 gold badges7 silver badges14 bronze badges 02 Answers
Reset to default 5I would reduce
the string into an object indexed by character. The function passed to reduce
is called for each element in the input, where the first argument (the a
) is the accumulator, which is either the initial value ({}
here) or what the last iteration returned. The second argument (the char
) is the current character being iterated over.
const str = "AbBAaaaa";
const charCounts = Array.prototype.reduce.call(str, (a, char) => {
a[char] = (a[char] || 0) + 1;
return a;
}, {});
console.log(charCounts);
You could also use
const charCounts = [...str].reduce((a, char) => // ...
which is shorter and probably a bit easier to understand at a glance, but unnecessarily creates an intermediate array from the str
.
The imperative version of this, with a for
loop, would look like:
const str = "AbBAaaaa";
const charCounts = {};
for (let i = 0; i < str.length; i++) {
const char = str[i];
charCounts[char] = (charCounts[char] || 0) + 1;
}
console.log(charCounts);
Javascript already has map and you can achieve same result of your C++ app as shown in this snippet
function charOccurances(str) {
var myMap = {};
if(str.length!==0){
for (let i = 0; i < str.length; i++) {
myMap[str[i]] = (myMap[str[i]] || 0) + 1;
}
}
return myMap;
}
const str = "AbABaaaa";
console.log(charOccurances(str));