3

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']);

2 Answers 2

2

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++;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks! it works! Could you tell me what is happening here? I'm guessing there's an index and that each tweet is going through it but I'm not sure.
You have an array of objects, but you acted as it was object of objects. And indexof could work only if you pass there the same object
loc.loation.locCount could work if you have var loc = { loation: { locCount: 1 } }; , and it couldn't make a grouping by tweet.user.location.
You also could use Array - find if it supported in all browsers, but it not working in IE : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . That's why I used reduce
0

Array.indexOf is not matching as you think it is. You're creating a new object and pushing it into the array, and regardless of whether its properties match a different object perfectly, it will not be === equal. Instead, you have to find it manually:

var foundLoc;
for (var i = 0; i < loc.length; i++) {
  if (loc[i].location.x === location.x) 
     foundLoc = loc[i];
     break;
  }
}
if (!foundLoc) { 
  loc.push({location: location, count: 0});
} else {
  foundLoc.count++
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.