I'm trying to write a function that when given a string, returns an object where each key is a word in the given string, with its value being how many times that word appeared in the given string.
Here's what I have:
function countWords(str) {
var strArray = str.split(' ');
var output = {};
if(str.length === 0) {
return output;
} else {
strArray.map(function(n) {
output[n] = str.split(n).length - 1;
});
}
return output;
}
Here's the console output when I add...
console.log(strArray);
console.log(output);
...to the code:
Object { a: 4, ask: 1, bunch: 3, get: 1, try: 1 } ["ask", "a", "bunch", "try", "a", "bunch", "get", "a", "bunch"]
For some reason, the number of occurrences of 'a' is 1 too high but all the others are correct.
Anyone see what I'm doing wrong?