use*_*609 2 javascript sorting collections unique count
我正在寻找一个简洁的JavaScript函数,它接受一些值并返回按出现次数排序的唯一值,最常见的是.
例如,如果输入是数组,[3,2,2,2,2,1,2,1]那么输出应该是[2,1,3].
Jam*_*son 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 ]
Run Code Online (Sandbox Code Playgroud)