Reputation: 690
var str = "abhishekkeshri"
var arr = str.split("")
var myMap = new Map();
console.log(arr)
//alert(arr)
var n = arr.length;
for (let i = 0; i < n; i++) {
var count = 0;
for (let j = i + 1; j < n; j++) {
if (arr[i] === arr[j]) {
count++;
console.log("inside loop " + arr[i] + " " + count)
}
myMap.set(arr[i], count);
}
}
myMap.forEach((key, value) => {
console.log(key + " " + value)
})
This is my code: I am trying to check the count of each alphabet in a string a storing the data on the map. But my Output is not the expected one. Can you point out my mistake? Also if there is any other better and optimized way to do please let me know
P.S. attaching my output
Upvotes: 2
Views: 87
Reputation: 386680
You could get the count from the map or zero and set the map to an incremented count without using an inner loop.
var str = "abhishekkeshri"
var arr = str.split("")
var myMap = new Map();
var n = arr.length;
for (let i = 0; i < n; i++) {
let count = myMap.get(arr[i]) || 0; // get count from map or take zero as default value
myMap.set(arr[i], count + 1); // add one for the actual character
}
myMap.forEach((value, key) => { // switch key/value
console.log(key + " " + value)
})
Upvotes: 4