我想删除数组中的所有重复项,并按照它们从大多数到最少的顺序排列
["57358e5dbd2f8b960aecfa8c",
"573163a52abda310151e5791",
"573163a52abda310151e5791",
"573163a52abda310151e5791",
"573163a52abda310151e5791",
"573163da2abda310151e5792",
"57358e5dbd2f8b960aecfa8c",
"57358e5dbd2f8b960aecfa8c"
"573163da2abda310151e5792",]
我想要这样
["573163a52abda310151e5791",
"57358e5dbd2f8b960aecfa8c",
"573163da2abda310151e5792"]
因为第一个出现最多次,然后是第二个然后第三个只出现一次
答案 0 :(得分:0)
当然,有一百万种不同的方法,但一个相当简单的方法是首先计算不同项目的出现次数,然后根据它对唯一值进行排序:
var input = [
"57358e5dbd2f8b960aecfa8c",
"573163a52abda310151e5791",
"573163a52abda310151e5791",
"573163a52abda310151e5791",
"573163a52abda310151e5791",
"573163da2abda310151e5792",
"57358e5dbd2f8b960aecfa8c",
"57358e5dbd2f8b960aecfa8c",
"573163da2abda310151e5792"
];
var count = {};
input.forEach(function(item) {
if(count.hasOwnProperty(item)) count[item]++;
else count[item] = 1;
});
var output = Object.keys(count).sort(function(left, right) {
if(count[left] < count[right]) return 1;
if(count[left] > count[right]) return -1;
return 0;
});
答案 1 :(得分:0)
您可以创建一组键值对(键,出现),如下所示:
var arr = [];
for (var i = 0; i < myArray.length; i++) {
if (arr.indexOf(myArray[i]) > -1) {
// It occured before, search the key-value pair
// and increment the occurance
arr.indexOf(myArray[i])[1]++;
} else {
// Add to our array
arr.push({myArray[i], 1});
}
}
function compare(a, b) {
if (a[1] < b[1]) return -1;
else if (a[1] > b[1]) return 1;
else return 0;
}
arr.sort(compare);
这样,您可以完全控制排序算法,并将确切的出现次数作为额外的奖励!希望这会有所帮助。