Ayushi Keshri
Ayushi Keshri

Reputation: 690

issue with map (data structure) in this code

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

output of the code:image

Upvotes: 2

Views: 87

Answers (1)

Nina Scholz
Nina Scholz

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

Related Questions