wootscootinboogie
wootscootinboogie

Reputation: 8695

jQuery word frequency counter

I've fried my brain looking at this for too long. With the following little JavaScript:

 var words = 'one two three four one two three';
        wordArray = words.split(' ');
        var newArray = [];
        var words = {};
        words.word;
        words.count;
        $.each(wordArray, function (ix, val) {
            if ($.inArray(wordArray[ix], newArray) > -1) {
                newArray[wordArray[ix]].count++;
            }
            else {
                console.log('that wasnt in the array');
                newArray.push(wordArray[ix]);
                newArray[wordArray[ix]].count = 1;
            }

        });

I get the error cannot set property 'count' of undefined. Why can't I dynamically add the property and have anything work fine?

Upvotes: 1

Views: 1100

Answers (2)

monastic-panic
monastic-panic

Reputation: 3997

seems like you are trying to invent a property count on the Array. I think you just want length unless newArray is something other then the native Array object. if it is just a ["word", "another"] then you don't need to do anything to increment the length property it is done internally

UPDATE ok then defninately the problem is the count property newArray.length will do what you are trying to do with .count

UPDATE 2

ok so it looks like you want to do this:

    var words = 'one two three four one two three';
    wordArray = words.split(' ');
    var newArray = [];
    var words = {};

    $.each(wordArray, function (ix, word ) {
        if ($.inArray(word , newArray) > -1) {
            words[word]++;
        }
        else {
            console.log('that wasnt in the array');
            words[word] = 1;
        }

    });

this would give you an object where the word is the key and the value is the count like:

{ "one": 2, "four": 1} //etc

Upvotes: 2

Barmar
Barmar

Reputation: 780818

newArray should be an object whose properties are the words and values are the count:

var newArray = {};
$.each(wordArray, function (ix, val) {
    if (newArray[val]) {
        newArray[val]++;
    }
    else {
        console.log('that wasnt in the array');
        newArray[val] = 1;
    }
});

Upvotes: 3

Related Questions