Count number of repetition for values in JSON nested arrays with Javascript

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Count number of repetition for values in JSON nested arrays with Javascript



I'm stuck with something I thought would be easy. Let's say I have an object like this. I'm trying to insert in the div each name of the animal tagged and the number of times that tag is in types (for example, cat = 3, etc...)




var animals = '';
animals =
"types": [

"id": "1",
"tags": ["cat"]
,

"id": "2",
"tags": ["dog"]
,

"id": "3",
"tags": ["cat", "bird", "dog"]
,

"id": "4",
"tags":
,

"id": "5",
"tags": ["cat", "bird"]

]


for (var i = 0; i < animals.length; i++)
var tags = animals[i].tags;


<div class="types">Number of animals:</div>



I'm a beginner with complex JSON objects, any help would be appreciated. It can be vanilla JS or Jquery.



Thanks!




7 Answers
7



Check out the snippet below, first loop iterates and counts each animal.



Second populates your div




var animals = '';
animals =
"types": [
"id": "1",
"tags": ["cat"]
,

"id": "2",
"tags": ["dog"]
,

"id": "3",
"tags": ["cat", "bird", "dog"]
,

"id": "4",
"tags":
,

"id": "5",
"tags": ["cat", "bird"]

]

var tags = ;

// Iterate over all your items
animals.types.forEach(function(type)
// Iterate over all the animals in the array
type.tags.forEach(function(tag)
if (tag in tags)
// If animal is present, increment the count
tags[tag] = tags[tag] + 1;
else
// If animal is not present, add the entry
tags[tag] = 1;

)
)

// Iterate over all the animals and add it to the div
for (var animal in tags)
if (tags.hasOwnProperty(animal))
document.getElementsByClassName('types')[0].innerHTML += ' ' + animal + ' ' + tags[animal];


<div class="types">Number of animals:</div>





Thank you! This answers my question perfectly.
– jmarc
Aug 14 at 16:09





Glad, I could help you out :)
– cdoshi
Aug 15 at 6:06



You can do like this by using map() method :


map()




var animals =
"types": [
"id": "1",
"tags": ["cat"]
,

"id": "2",
"tags": ["dog"]
,

"id": "3",
"tags": ["cat", "bird", "dog"]
,

"id": "4",
"tags":
,

"id": "5",
"tags": ["cat", "bird"]

]
;

var count = ;
animals.types.map(function (arr, i)
arr.tags.map(function (tag, k) );
);
console.log(count);



If you use reduce & destrucuring it becomes one liner:




var animals =
"types": [
"id": "1",
"tags": ["cat"]
,

"id": "2",
"tags": ["dog"]
,

"id": "3",
"tags": ["cat", "bird", "dog"]
,

"id": "4",
"tags":
,

"id": "5",
"tags": ["cat", "bird"]

]


console.log(
animals.types.reduce((r,tags) => tags.map(tag => r[tag] = (r[tag] || 0) + 1) && r, )
)





Why do you need the && r?
– skylerfenn
Aug 13 at 14:02


&& r





You need to return r from the reduce and && r does it :)
– Akrion
Aug 13 at 15:31


r


&& r





Oh duh, very cool, thanks!
– skylerfenn
Aug 13 at 15:32



Try this simple way:


var animals = "types": [ "id": "1", "tags": ["cat"] , "id": "2", "tags": ["dog"] , "id": "3", "tags": ["cat", "bird", "dog"] , "id": "4", "tags": , "id": "5", "tags": ["cat", "bird"] ]
var finalRes=;
animals.types.map(function(o, i)
o.tags.map(function(p, j));
);
console.log(finalRes);



Result:


cat: 3, dog: 2, bird: 2



Sorry, I am typing with mobile phone, slow but correct!




const animals =
"types": [

"id": "1",
"tags": ["cat"]
,

"id": "2",
"tags": ["dog"]
,

"id": "3",
"tags": ["cat", "bird", "dog"]
,

"id": "4",
"tags":
,

"id": "5",
"tags": ["cat", "bird"]
,
],
;

// Flatten all tags into single array

var allTags = .concat(
...animals.types.map(
(type) => type.tags
)
);

// Count each tag

const tagsCount = ;

allTags.forEach(
(tag) => tagsCount[tag] = tagsCount[tag] ? tagsCount[tag] + 1 : 1
)

// Handle tag count as you need

const app = document.querySelector('#app');

app.innerHTML = Object.keys(tagsCount).map((key) =>
return `<p>$key: $tagsCount[key]</p>`
).join('');


<h1>Number of Animal Types</h1>

<div id="app"></div>



Basic javascript usage.




// var animals = ''; // not needed
var animals =
"types": [
"id": "1",
"tags": ["cat"]
,

"id": "2",
"tags": ["dog"]
,

"id": "3",
"tags": ["cat", "bird", "dog"]
,

"id": "4",
"tags":
,

"id": "5",
"tags": ["cat", "bird"]

]
;

var counts = ;
for (var i = 0; i < animals.types.length; i++) // types is a key in animals object, animals is not an array
var tags = animals.types[i].tags;
if (tags.length > 0)
for (var j = 0; j < tags.length; j++)
var tag = tags[j];
if (typeof counts[tag] === 'undefined')
counts[tag] = 0;

counts[tag]++;





console.log(counts);



You could create a hash map for all the tags and increment the count whenever you encounter that tag in that types.tags array


hash map


types.tags



Then loop through the object and append that into your HTML Element




var animals = '';
animals =
"types": [

"id": "1",
"tags": ["cat"]
,

"id": "2",
"tags": ["dog"]
,

"id": "3",
"tags": ["cat", "bird", "dog"]
,

"id": "4",
"tags":
,

"id": "5",
"tags": ["cat", "bird"]

]

let types = animals.types;
var counts = ;

for (var i = 0; i < types.length; i++)
types[i].tags.forEach((x) =>
counts[x] = (counts[x] );

console.log(counts);


<div class="types">Number of animals:</div>






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS