Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of times a string is repeated in array using Lodash

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.

like image 734
Koder Avatar asked Jan 17 '18 06:01

Koder


1 Answers

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>
like image 163
klugjo Avatar answered Sep 19 '22 12:09

klugjo