-2
function problem14(){
    var count=0;
    var input1 = document.getElementById('input14').value;
    for(var i=0; i<input1.length; i++){
        for(var j=0; j<input1.length; j++){
            if(input1.charAt(i)==input1.charAt(j)){
                //What to Write Here ? 
                //If I do Write So far
            }
        }
    }
    document.getElementById('problem14').innerHTML = count;
}

Plz Help Guyss What to Write ... Where I Use Comments..

3 Answers3

1
  1. Get string and split to array
  2. Loop array and add values from array in key in object. If a key with this value has already been created, +1 will be added as the value of this key.

I hope this code works for you.

Example with forEach:

function counter(par) {
    var spar = par.split('');
    var cnt = {};
    spar.forEach(function (x) { 
        cnt[x] = (cnt[x] || 0) + 1; 
    });
    return cnt;
}

console.log(counter("aabsfgssdfg"));

Example with for of:

function counter(par) {
    var spar = par.split('');
    var cnt = {};
    for (var i of spar) {
        cnt[i] = (cnt[i] || 0) + 1;
    }
    return cnt;
}

console.log(counter("aabsfgssdfg"));
54ka
  • 3,501
  • 2
  • 9
  • 24
0

basically what you need to do is to have an object where to store the additions of each letter, after that you can compare if you already have it then you add 1, if there is no entry for that, you start with 1.

take a look to the comments, you will see how it works

function problem14() {
  // to hold all the letter repetitions
  const letters = {};

  // to get the value that the user enters
  let input1 = document.getElementById('input14').value;

  // loop over the input text
  for (let i = 0; i < input1.length; i++) {
    // save the letter that we are looking
    let currentLetter = input1[i];

    // lets compare, if the current letter is already counted we add 1
    if (letters[currentLetter]) {
      letters[currentLetter] += 1;
    } else {
      // this means the letter was not in our object, so we initialize it using 1
      letters[currentLetter] = 1;
    }
  }

  // the JSON.stringify function is just to show it in a readable way
  document.getElementById('result').innerHTML = JSON.stringify(letters, null, 4);
}


document.getElementById("button").addEventListener("click", function() {
  problem14();
});
<input id="input14">
</br>
<button id="button"> count </button> 
</br>
result: <label id="result"></label>
Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19
0
function problem14(){
var count=0;
var input1 = document.getElementById('input14').value;
var hashTable = {}
for (var i= 0 ; i < input1.length; i++) {
    if (hashTable[input1[i]]) {
         hashTable[input1[i]] += 1
    } else {
        hashTable[input1[i]] = 1
    }
  }
}

hashTable object will contain the charaters and their count