Sorry. I was previously thinking like Excel rather than Google Sheets. This can be done more directly in Google Sheets using its ability to construct arrays.
Deconstructing that, unique(B1:B40) are the distinct items from B1:B40 in order of 1st appearance. countif(B1:B40,unique(B1:B40)) is the number of occurrences of each distinct item. The Google Sheets gem is {countif(B1:B40,unique(B1:B40)),unique(B1:B40)} which is a constructed array the 1st column of which are the number of occurrences of each distinct, and the 2nd column of which are the distinct items. The SORT call sorts that constructed array on its 1st column in descending order. The INDEX call removes the 1st column, leaving only the distinct items in order of most to least occurrences, and TEXTJOIN groups them into a comma-separated list in a single cell.
Bookmarks