Paulos3000 Paulos3000 - 1 year ago 74
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
is referring to the
variable. I've tried declaring this both within and before the loop (as
), but this doesn't work.

Is it something to do with
being returned as a string and therefore not being set properly as a property of

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

Answer Source

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 ...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download