Unique counts in JavaScript array, sorted by counts
I have a list of names in JavaScript. What I'd like to do is get the list of unique names, but for that list of unique names also provide a count of how many there are in my original list. Furthermore, I need to sort my final list of unique names by count in descending order (then ascending order by name in case some have the same counts).
Here's what I have which is just a simple list of strings, that then gives me the list of unique names. From here, I'm not sure where to get the counts or how to then sort the unique list by counts. I'm thinking the final result will be either a 2D array of names and counts or 2 separate arrays, but I'm not sure how to go about this the best and most efficient way.
This is what I have so far:
Array.prototype.contains = function(v) {
for (var i = 0; i < this.length; i++) {
if (this[i] === v) return true;
}
return false;
};
Array.prototype.unique = function() {
var arr = [];
for (var i = 0; i < this.length; i++) {
if (!arr.contains(this[i])) {
arr.push(this[i]);
}
}
return arr;
}
var uniqueAuthorNames = allAuthorNames.unique();
uniqueAuthorNames.sort();
使用散列图来计算唯一元素,然后按以下两个条件对唯一元素进行排序:
var names = ["eve", "carl", "adam", "carl"];
var counts = names.reduce((counts, name) => {
counts[name] = (counts[name] || 0) + 1;
return counts;
}, {});
var uniques = Object.keys(counts);
uniques.sort((a, b) => counts[a] == counts[b] ? a.localeCompare(b) : counts[b] - counts[a]);
console.log(counts);
console.log(uniques);
Supposing your array of names is in arr :
var i;
var o = {};
var len = arr.length;
for (i=0; i<len; i++) {
o[arr[i]] = (o[arr[i]] || 0) + 1;
}
At this stage, o will hold every unique name, with its count. You can then use the solution in Sorting JavaScript Object by property value
This will be
var sortable = [];
for (var name in o) {
sortable.push([name, o[name]])
}
sortable.sort(function(a, b) {return b[1] - a[1]})
This should be working for what you need.
Object.defineProperty (Array.prototype, 'getUniqueSorted', {
enumerable: false,
value: function () {
var uniqarr = [];
for (var i in this) {
var index = uniqarr.indexOf (this.[i]);
if (index == -1) {
uniqarr.push (this [i])
} else {
uniqarr [index].count = uniqarr.count ? 2 : uniqarr.count+1;
}
}
uniqarr = uniqarr.sort(function(a, b){
return (a.count | 1) - (b.count | 1)
});
return uniqarr;
}
});
There's some other options to make more elegant.
Object.defineProperty (Array.prototype, 'removeDuplicated', {
enumerable: false,
value: function () {
var uniqarr = [];
this.reduce(function(accum, current) {
if (accum.indexOf(current) < 0) {
accum.push(current);
}
return accum;
}, uniqarr);
return uniqarr.sort(function(a, b){
return a.count - b.count
});
}
});
链接地址: http://www.djcxy.com/p/19048.html
上一篇: 将JSON平坦化为没有ID的层次结构/树