I have an array of strings which are tags of blog posts from database.
This is the example end result of a query :
["apple","banana", "apple", "orange","grapes","mango","banana"];
I need to know how many times a string is repeated in that array so I can build a sort of tag cloud.
Final end result should look like: [{name:"apple",count:2}, {name:"banana", count:2}, {name: "orange",count:1} ...];
I am using lodash in my project and would like to use it if possible. plain javascript is also fine.
You can use groupBy to do the heavy lifting then use map to format the result to your liking:
const data = ["apple", "banana", "apple", "orange", "grapes", "mango", "banana"];
const result = _.values(_.groupBy(data)).map(d => ({name: d[0], count: d.length}));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With