Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript function returning unique values sorted by count

I am looking for a concise JavaScript function which takes some values and returns the unique values sorted by the number of occurrences, the most frequent first.

For example, if the input is the array [3,2,2,2,2,1,2,1] then the output should be [2,1,3].

like image 936
user1069609 Avatar asked Dec 01 '25 06:12

user1069609


1 Answers

Here's my first stab. I bet we can make it simpler, but this seems okay.

 function fancyUnique(arr) {

   var counts = {}; // store counts for each value
   var fancy = []; // put final results in this array
   var count = 0; // initialize count

   // create counts object to store counts for each value of arr
   for (var i = 0; i < arr.length; i++) {
     count = counts[arr[i]] || 0;  // use existing count or start at 0
     count++; // increment count
     counts[arr[i]] = count; // update counts object with latest count
   }

   // take all keys from counts object and add to array
   // also: object keys are string, so must parseInt()
   for (var key in counts) {
     fancy.push(parseInt(key, 10)); 
   }

   // sort results array in highest to lowest order
   return fancy.sort(function(a, b) { 
     return counts[b] - counts[a]; 
   })
 }


fancyUnique([22,22,1,1,1,1]) // [ 1, 22 ]
like image 176
Jamund Ferguson Avatar answered Dec 03 '25 18:12

Jamund Ferguson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!