heliu heliu - 24 days ago 7
Javascript Question

How can i access this object key in this conditional?

Write a function countWords that, when given a string as an argument, returns an object where keys are the words in the string, and values are the number of occurrences of that word within the string:

function countWords(string){
string = string.split(" ");
var newObj = {};
for(var i = 0 ; i === newObj.string ; i++){
if(newObj['i'] === newObj[string]){
newObj[string[i]] = i ;
}
}
return newObj;
}
countWords("hello hello"); // => {"hello": 2}
countWords("Hello hello"); // => {"Hello": 1, "hello": 1}
countWords("The quick brown"); // => {"The": 1, "quick": 1, "brown": 1}


I realized since you do not need to count the index of the split string, you have to change the conditions from i < string.length to i === key value of of the objects. Why can't I access the strings with newObj.string?

Answer

You could do this with reduce() instead of for loop.

function countWords(string) {
  return string.split(' ').reduce(function(r, e) {
    r[e] = (r[e] || 0) + 1;
    return r;
  }, {})
}
console.log(countWords("hello hello"))
console.log(countWords("Hello hello"))
console.log(countWords("The quick brown"))

With for loop your code could go like this.

function countWords(string) {
  var string = string.split(" ");
  var newObj = {};

  for (var i = 0; i < string.length; i++) {
    newObj[string[i]] = (newObj[string[i]] || 0) + 1
  }
  return newObj;
}
console.log(countWords("hello hello"));
console.log(countWords("Hello hello"));
console.log(countWords("The quick brown"));