I am writing a function called "countStr".
I need to return 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. If the string is empty it must return an empty object.
Here's my function so far:
function countStr(str) {
myObject = {};
if(str.length === 0) {
return myObject;
} else {
myArray = str.split(' ');
for(var i = 0; i < myArray; i++) {
var key = myArray[i];
if(myObject.hasOwnProperty(key)) {
myObject[key]++;
} else {
myObject[key];
}
}
return myObject;
}
}
var output = countStr('ask me lots get me lots');
console.log(output); // --> IT MUST OUTPUT {ask: 1, me: 2, lots: 2, get: 1}
Can you tell me how to fix it?
myArray