7

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.

4 Answers 4

10

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>

Sign up to request clarification or add additional context in comments.

Comments

2

Use reduce and map

var input = ["apple","banana", "apple", "orange","grapes","mango","banana"];

var map = input.reduce( (a,c) => ( a[c] = a[c] || 0, a[c]++, a ) ,{});

var output = Object.keys( map ).map( s => ({name: s, count:map[s]}) );

Demo

var input = ["apple", "banana", "apple", "orange", "grapes", "mango", "banana"];

var map = input.reduce((a, c) => (a[c] = a[c] || 0, a[c]++, a), {});

var output = Object.keys(map).map(s => ({
  name: s,
  count: map[s]
}));

console.log(output);

1 Comment

Your answer is correct, however @klugjo's answer is more readable.
0

Create a map, mapping name to count. Loop over the list, for each item, if its' in the map, increment it's count, else set its count to one.

if (tag in map) { map[tag] += 1 }
else { map[tag] = 1 }

Then you can iterate of the map and convert it to a list of objects.

Comments

0

To count use _.countBy(), then transform to requested form, by using _.entries(), and mapping the tuples to objects:

const data = ["apple", "banana", "apple", "orange", "grapes", "mango", "banana"];

const result = _.entries(_.countBy(data)).map(([name, count]) => ({ name, count }));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.