Paulos3000 Paulos3000 - 4 months ago 10
Javascript Question

Assigning array elements as object properties, with 'counter' value

I'm trying to write a method that takes the words in a sentence, lists the different words, and the number of times they occur, but I can't get it to work.

This is what I have so far:

var wordsArr = ['one', 'fish', 'two', 'fish', 'red', 'fish', 'blue', 'fish']
var wordsObj = {};
for (var i = 0; i < wordsArr.length; i++) {
var counter = 0;
wordsObj.wordArr[i] = counter++;
}
return wordsObj;


At the end of it I'm hoping to see this returned:

{ one : 1, fish : 4, two : 1, red : 1, blue : 1 }


My console is telling me,


'Uncaught TypeError: Cannot set property '0' of undefined'


I assume
undefined
is referring to the
counter
variable. I've tried declaring this both within and before the loop (as
0
), but this doesn't work.

Is it something to do with
wordsArr[i]
being returned as a string and therefore not being set properly as a property of
wordsObj
?

If anyone can tell me where I'm going wrong I'd appreciate it. Thanks in advance.

Answer

the property will keep track of the counted instances so you don't need a counter variable:

var wordsArr = ['one', 'fish', 'two', 'fish', 'red', 'fish', 'blue', 'fish']
var wordsObj = {};
for (var i = 0; i < wordsArr.length; i++) {
   //var counter = 0;
   wordsObj[wordsArr[i]] = ( wordsObj[wordsArr[i]] || 0 ) + 1;
}
console.log( wordsObj );

apart form that you had some minor syntax errors ...