0

I have a function which produces the result of a string into an object with the letters counted as values of the properties in a key/value format.

var output = countAllCharsIntoObject('banana');
console.log(output); // --> {b: 1, a: 3, n: 2}

My issue is that beside the looping of an array of the string

function countAllCharsIntoObject(str){
    var arr = str.split('');
    var obj = {};
    for(var i = 0; i < arr.length; i++) {
        //how to iterate the arr[i] and assign the value of the chars to the       
        //keys/values of the new obj. And if more then 1 indexOf(arr[i]) then   
        //change through an iteration the value of the new char key.I tried so   
        //many solutions without effect.
    }
    return obj;
}

Just can not wrap my mind around the fact that i simultaneously loop within a loop with assignment to key/values of the results of the loop (with dynamic increment of values). Any help would be appreciated! Just in plain JS please... no underscore or lodash or jQuery solutions. Thanks!

Morteza Asadi
  • 1,819
  • 2
  • 22
  • 39

2 Answers2

0

You just need to iterate through each character in your word and either add a new key to your object, or increment an existing key:

function countAllCharsInObject (word) {
  var letterCounts = {};
  var currentLetter;
  for (var i = 0; i < word.length; i++) {
    currentLetter = word[i];
    if (currentLetter in letterCounts) {
      letterCounts[currentLetter] += 1;
    } else {
      letterCounts[currentLetter] = 1;
    }
  }
  return letterCounts;
}
hackerrdave
  • 6,486
  • 1
  • 25
  • 29
0

Simplified code:

var output = countAllCharsIntoObject('banana');
console.log(output); // --> {b: 1, a: 3, n: 2}

function countAllCharsIntoObject(str) {

  var arr = str;
  var obj = {};
  for (var i = 0; i < arr.length; i++) {

    obj[arr[i]] = obj[arr[i]] + 1 || 1
  }
  return obj;
}
Sandeep Nayak
  • 4,649
  • 1
  • 22
  • 33