Reputation: 5
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?
Upvotes: 0
Views: 45
Reputation: 2228
function countStr(str) {
myObject = {};
var myArray = [];
if(str.length === 0) {
return myObject;
} else {
myArray = str.split(' ');
for(var i = 0; i < myArray.length; i++) {
var key = myArray[i];
if(myObject.hasOwnProperty(key)) {
myObject[key]++;
} else {
myObject[key]=1;
}
}
return myObject;
}
}
var output = countStr('ask me lots get me lots');
console.log(output);
Upvotes: 0
Reputation: 31467
There are small issues with your code.
length
of the array.else
case.var
to avoid polluting your top level namespace.Here is the fixed version:
function countStr(str) {
var myObject = {};
if(str.length === 0) {
return myObject;
} else {
var myArray = str.split(' ');
for(var i = 0; i < myArray.length; i++) {
var key = myArray[i];
if(myObject.hasOwnProperty(key)) {
myObject[key]++;
} else {
myObject[key] = 1;
}
}
return myObject;
}
}
var output = countStr('ask me lots get me lots');
console.log(output);
Upvotes: 2
Reputation: 13943
You can use Array#reduce()
like this
function countStr(str) {
return str.trim().length ? str.split(' ').reduce((o,s)=>{
o[s] = o[s] || 0;
o[s]++;
return o;
}, {}) : {};
}
var output = countStr('ask me lots get me lots');
console.log(output); // --> {ask: 1, me: 2, lots: 2, get: 1}
Other wise in your code, you were missing Array.length
in your for
condition and the else
should be like myObject[key]=1
Upvotes: 1