Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Creates new array instead of incrementing

Tags:

javascript

I'm making a simple twitter app to work on my javascript. The code below is supposed to identify every tweets location and count the number of tweets per location.

However, it doesn't increment, it just creates a new array. What is wrong with my code? How can I make it better?

Thank you

var Twitter = require('node-twitter'),
twit = {},
loc = [];

twit.count = 0;


var twitterStreamClient = new Twitter.StreamClient(
//credentials
);

twitterStreamClient.on('close', function () {
    console.log('Connection closed.');
});
twitterStreamClient.on('end', function () {
    console.log('End of Line.');
});
twitterStreamClient.on('error', function (error) {
    console.log('Error: ' + (error.code ? error.code + ' ' + error.message : error.message));
});
twitterStreamClient.on('tweet', function (tweet) {


    if (loc.indexOf(tweet.user.location) === -1) {
        loc.push({"location": tweet.user.location, "locCount": 1});
    } else {
        loc.loation.locCount = loc.loation.locCount + 1;
    }


    console.log(loc);

});

var search = twitterStreamClient.start(['snow']);
like image 446
nickfrenchy Avatar asked Sep 24 '26 12:09

nickfrenchy


1 Answers

You need to rewrite on tweet callback:

var index = loc.reduce(function(acc, current, curIndex) {
   return current.location == tweet.user.location ? curIndex : acc;
}, -1);

if (index === -1) {
    loc.push({"location": tweet.user.location, "locCount": 1});
} else {
    loc[index].locCount++;
}
like image 182
Dmitry Yaremenko Avatar answered Sep 26 '26 01:09

Dmitry Yaremenko