I'm interested in analyzing a JSON array to find the occurrences of a specific item by date. Let me demonstrate with the following JSON example:
"data": [
{
"tags": [
"foo",
"bar",
"hello",
"world",
"alice"
],
"date": [
1402876800000
],
...
},
{
"tags": [
"foo",
"world",
"alice"
],
"date": [
1402963200000
],
...
}
My goal is to create a function that takes a tag as input ('foo' for instance) and displays how many times that tag appears on a particular date in the HTML. So if we call tagOverTime('foo')
, the result would be something like this:
06/16/14 - 14 occurrences
06/17/14 - 8 occurrences
I also intend to format the dates, but I believe I can handle that part using toLocaleDateString()
. Currently, I am able to iterate through the array, but not much beyond that. Here is my progress so far:
$.getJSON('mydata.json', function(data) {
function containsObject(obj, list) {
var i;
for (i = 0; i < list.length; i++) {
if (list[i] === obj) {
return true;
}
}
return false;
}
function tagOverTime(tagToSearch) {
var output="<h4>" + tagToSearch + "</h4><ul>";
for(var i = 0 ; i< data.data.length; i++){
var obj = data.data[i];
var tagsArray = obj["tags"];
// make sure tag array isn't empty
if( tagsArray != undefined ) {
// then iterate through it
for(var j = 0; j < tagsArray.length;j++ ){
// if that tag exists in the given tags array, check its date and count up somehow
if(tagsArray[j] == tagToSearch){
output+='<li>' + obj.date + '</li>';
}
}
}
}
output+="</ul>";
document.getElementById("output").innerHTML=output;
}
tagOverTime('foo');
Although the code currently generates an unordered list of dates, it doesn't accurately calculate the occurrence counts for specific dates. I acknowledge this flaw as I wrote the code and am now seeking a solution to effectively tally up occurrences on individual dates.