zasman
zasman

Reputation: 486

Javascript: Looping through the characters of elements in an array

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?

Upvotes: 2

Views: 3167

Answers (3)

gevorg
gevorg

Reputation: 5055

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

Upvotes: 2

timolawl
timolawl

Reputation: 5564

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>

Upvotes: 1

Nenad Vracar
Nenad Vracar

Reputation: 122047

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)

Upvotes: 1

Related Questions