Displaying Top Hashtags by sorting Hashtags based on the frequency
It is a good idea to display top hashtags on sidebar of loklak. To represent them, it is really important to sort out all unique hashtags on basis of frequency from results obtained from api.loklak. The implementation of the process involved would be discussed in this blog.
Raw Hashtag result
The Hashtags obtained as a parameter of type array containing array of strings into the sortHashtags() method inside the component typescript file of Info-box Component is in Raw Hashtag form.
Making Array of all Hashtags
Firstly, all the Hashtags would be added to a new Array – stored.
sortHashtags( statistics ) { let stored = []; if (statistics !== undefined && statistics.length !== 0) { for (const s in statistics) { if (s) { for (let i = 0;i < statistics[s].length; i++) { stored.push(statistics[s][i]); } } } } }
stored.push( element ) will add each element ( Hashtag ) into the stored array.
Finding frequency of each unique Hashtag
array.reduce() method would be used to store all the Hashtags inside the stored array with frequency of each unique Hashtag (e.g. [ ‘Hashtag1’: 3, ‘Hashtag2’: 2, ‘Hashtag3’: 5, … ]), where Hashtag1 has appeared 3 times, Hashtag2 appeared 2 times and so on.
stored = stored.reduce(function (acc, curr) { if (typeof acc[curr] === ‘undefined’) { acc[curr] = 1; } else { acc[curr] += 1; } return acc; }, []);
stored.reduce() would store the result inside stored array in the format mentioned above.
Using Object to get the required result
Object would be used with different combination of associated methods such as map, filter, sort and slice to get the required Top 10 Hashtags sorted on the basis of frequency of each unique Hashtag.
this.topHashtags = Object.keys(stored) .map(key => key.trim()) .filter(key => key !== ”) .map(key => ([key, stored[key]])) .sort((a, b) => b[1] – a[1]) .slice(0, 10);
At last, the result is stored inside topHashtags array. First map method is used to trim out spaces from all the keys ( Hashtags ), first filter is applied to remove all those Hashtags which are empty and then mapping each Hashtag as an array with a unique index inside the containing array. At last, sorting each Hashtag on basis of the frequency using sort method and slicing the results to get Top 10 Hashtags to be displayed on sidebar of loklak.
Testing Top Hashtags
Search something on loklak.org to obtain sidebar with results. Now look through the Top 10 Hashtags being displayed on the Sidebar info-box.
Resources
- Tutorials Point: TypeScript – Array filter()
- Coderwall: Array native