2

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

2
  • 1
    what is expected output? Commented Oct 2, 2019 at 6:59
  • taking out the counts of no of occurance of eachalphbets in the string, like h is 3 times, i is 2 times a is 1 time. Commented Oct 2, 2019 at 7:19

1 Answer 1

4

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)
})

Sign up to request clarification or add additional context in comments.

1 Comment

this is the best solution i can get. Thanks for making it this easy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.