JavaScript函数返回按count排序的唯一值

时间:2012-02-14 16:20:05

标签: javascript sorting collections count unique

我正在寻找一个简洁的JavaScript函数,它接受一些值并返回按出现次数排序的唯一值,最常见的是。

例如,如果输入是数组[3,2,2,2,2,1,2,1],则输出应为[2,1,3]

2 个答案:

答案 0 :(得分:17)

这是我的第一次尝试。我敢打赌,我们可以让它更简单,但这似乎没问题。

 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 ]

答案 1 :(得分:0)

var data=[3,2,2,2,2,1,2,1];
console.log(countUnique(data));

function countUnique(data){
  var count={};
  $(data).each(function(index){                      
       count[data[index]] = count[data[index]]+1 || 1;             
  });
  return count;
}

output =“Object {1:2,2:5,3:1}”

这也适用于字符串。

可以使用以下循环

来读取输出
   for(var key in count)
    {
             console.log(key); // prints the index of the array
             console.log(count[key]); //prints the number of occurrences  

    }