I have some data that looks like this:
{
"data": [
{
"tags": [
"design",
"development",
"code",
"foo",
"bar"
],
"views": [
"81"
]
...
},
{
"tags": [
"design",
"foo",
"photoshop",
"alice",
"bob"
],
"views": [
"28"
]
...
}
What I’m hoping to do is loop through each data item, count up the tags, and then display how many times each one occurs. I don’t want to go query each tag manually, though.
So ideally, I’d like it to display like this:
foo: 2
design: 2
alice: 1
and so on. Eventually, I’m hoping to incorporate it into a chart using Highcharts, Amcharts, or something similar?
The closest I’ve managed is this, taken from another solution on this site (and this doesn’t create a full display, but I was first trying to get to grips with counting the values themselves, in any way possible):
$.getJSON('myarray.json', function(data) {
var occurrences = 0;
for (var i = 0; i < data.data.length; i++) {
if (data.data[i].tags == "foo") {
occurrences++;
}
}
console.log(occurrences);
});
But this output is incorrect. Any help at all would be appreciated. Once again, I would like to look through the tags for each dataset, and output a count for how many times each one occurs (ideally ranked in descending order).
5
Answers
You correctly loop through each item, but you forget that “tags” in each item is a list of items as well.
You can get the result you want with iterating over your data, I’ve taken your data like so as an example:
Then we can iterate over it like so:
Console log would output
jsFiddle: http://jsfiddle.net/602puhja/
http://jsfiddle.net/v0rhxvff/
You have to use a dictionary to count all the occurrences, then roll it in an array and sort it (if you want the same result as your output:
The solution is a bit long due to explanation purposes. You can take this and optimise to your needs in case by shortening some bits.