如何在javascript数组中获得具有最高出现次数(模式)的前5个元素

时间:2016-06-03 02:09:04

标签: javascript arrays

我想在JavaScript数组中获得具有最高出现次数(模式)的前5个元素。我找到了一个如何获得最高元素而不是前5或前10的元素片段。

以下是获取最高出现次数的代码段:

$('.pi-accordion-title').each(function() {
    this.innerHTML = this.innerHTML.replace(/(\(Keyword\))/, '<span class="orange">$1</span>');
});

2 个答案:

答案 0 :(得分:5)

首先,构建key =&gt;的地图计数条目

let counts = arr.reduce((map, fruit) => {
    map[fruit] = (map[fruit] || 0) + 1;
    return map;
}, {});

然后从键

创建一个排序数组
let sorted = Object.keys(counts).sort((a, b) => counts[b] - counts[a]);

然后采取前5

let top5 = sorted.slice(0, 5);

传统版本(如果需要)

var counts = arr.reduce(function(map, fruit) {
    map[fruit] = (map[fruit] || 0) + 1;
    return map;
}, {});

var sorted = Object.keys(counts).sort(function(a, b) {
    return counts[b] - counts[a];
});

var top5 = sorted.slice(0, 5);

答案 1 :(得分:0)

JSBin Example

var a = [1,2,3,4,5,1,2,3,4,5,6,7,8,9,1,2,3,4,6,6,6,7,5];

// make map:
var m = a.reduce(function(a, b) {
  a[b] = ++a[b] || 1;
  return a;
}, {});

// loop through object, get array of keys/values:
var arr = [];
for (var key in m) {
  arr.push([key, m[key]]);
}
// sort array by values:
arr.sort(function(a, b) {
  return a[1] - b[1];
});
// slice and map over 5 highest and return value:
console.log(arr.slice(-5).map(function(e) {
  return e[0];
}));