So I have this project where I'm collecting location data from a web socket. I need to find out which continent has the greatest hit rate. So in order to do this, I'm iterating through each location object. Now here's the part where I'm stuck... What's the best way to generate a dynamic array and add a hit value each time that the location object has that specific continent.
Originally I had a switch statement that had the continents predefined and check if the continent name exists, if it does, then it increments the value of that continent. Now, I want to make the location name dynamic, which puts my switch statement out of work.
Ok so here's my thought process so far... One way could be: create an empty array (let's say continentArray), grab the continent name, check if the continent name exists in continentArray, if it does, increment the value of the continent in continentArray. If it does not exist, create new array element (in continentArray) and increment the value.
Then the next part would be to display this data in a 3 x 2 column (HTML5 - using Bootstrap). I figured I could just give each div header an id (say rank1-5) and then each column content a separate id (say rankCont1-5) and populate each section based on each array key and value.
Would that be the best method?... Would it be better to create an object instead of array?
I saw this post and figured there has to be a way to do something similar: How do you 'search' an array of arrays in javascript?
An example of a data object is:
{
"country" : "US",
"continent" : "North America"
}
So here's my code so far:
var contArr = [];
socket.on('data', function(data)
{
//iterate through the socket data
for(var i=0;i<data.length;++i){
//define each iteration as item
var item = data[i];
//get current continent name
var continent = item.continent;
if (contArr[i] instanceof Array){
contArr[i]['val']++;
console.log(contArr[i]['val']);
}
else{
contArr[i] = continent;
contArr[i]['val'] = 1;
console.log(contArr[i]['val']);
}
}
});
Right now it's saying val is undefined, which makes sense. I'm just not sure how you do this correctly...
Any advise?...
Thanks!