2

I have the following problem:

Write a function that takes in a list of words, and returns an object that tells you how many times each letter showed up.

So something like this:

var data = ['hat', 'cat', 'dog'];

becomes:

var object = {
  'a' : 2,
  'h' : 1,
  't' : 2,
  'c' : 2,
  'd' : 1,
  'g' : 1
};

My solution thus far has been to:

  1. Create a function with a blank object.
  2. Loop through all the elements of the array

These steps aren't working like I think they were:

  1. Try to loop through the characters of each array element.
  2. If the character of the array element is undefined in the object, put it in and increment to one. Otherwise if its already there, increment it by one again.

Where am I going wrong? Or am I way off?

4
  • 1
    "Where am I going wrong" - you "forgot" to read How to Ask Commented May 4, 2016 at 22:27
  • add your code please Commented May 4, 2016 at 22:28
  • join the array into a string so you don't have to use two loops. Commented May 4, 2016 at 22:33
  • What Andy is suggesting is the best solution. Just put all of your array values into a string and then parse the string for individual character counts. Commented May 4, 2016 at 22:34

3 Answers 3

2

This is what you are searching for:

// Function that you need.
function letterUsage(data) {
    // Collector.
    var result = {};
    
    // Loop.
    for (var i = 0; i < data.length; ++i) {
        for (var j = 0; j < data[i].length; ++j) {
            var letter = data[i][j];
            if (result[letter]) {
                result[letter] = result[letter] + 1;
            } else {
                result[letter] = 1;
            }
        }
    }

    return result;
}

// Prepare test.
var data = ['hat', 'cat', 'dog'];
var result = letterUsage(data);

// Print result.
console.log(result);

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

1 Comment

Exactly how I wanted to do it. Thank you sir!
1

You can do this with one Reduce just first join array to one string and then split it on each letter

var data = ['hat', 'cat', 'dog'];

data = data.join('').split('').reduce(function(sum, el) {
  sum[el] = (sum[el] || 0) + 1;
  return sum;
}, {});

console.log(data)

Comments

1

Array.prototype.forEach alternative:

var data = ['hat', 'cat', 'dog'];

var object = {};

data.join('').split('').forEach(letter => { object[letter] = ++object[letter] || 1;});

document.querySelector('pre').textContent = JSON.stringify(object, 0, 4);
<pre></pre>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.