nickfrenchy
nickfrenchy

Reputation: 283

Javascript - Creates new array instead of incrementing

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

Upvotes: 3

Views: 80

Answers (2)

Dmitry  Yaremenko
Dmitry Yaremenko

Reputation: 2570

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++;
}

Upvotes: 2

tanenbring
tanenbring

Reputation: 780

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++
}

Upvotes: 0

Related Questions