Reputation: 486
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:
These steps aren't working like I think they were:
Where am I going wrong? Or am I way off?
Upvotes: 2
Views: 3167
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
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
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