通过最常见的项目在javascript中排序数组

时间:2016-12-26 16:22:07

标签: javascript arrays sorting

我有一个字符串数组:

array = ["Henry","Brian","Henry","Matilda","Henry","Brian","Matthew"]

并希望将它们排序到一个列表中,该列表首先通过最常见的项目对数组进行排序,但之后也会删除它们以创建如下列表:

sortedArray = ["Henry","Brian","Matilda","Matthew"]

有没有办法在javascript中执行此操作?

5 个答案:

答案 0 :(得分:6)

你可以使用这个在 O(nlogn)中运行的ES6功能,而不是 O(n²)作为其他一些解决方案:

var array = ["Henry","Brian","Henry","Matilda","Henry","Brian","Matthew"]

var result = [...array.reduce( (acc, s) => acc.set(s, (acc.get(s) || 0)+1), new Map )]
    .sort( (a, b) => b[1] - a[1] )
    .map( a => a[0] );

console.log(result);

首先通过保持每个字符串的计数(以线性时间运行)来创建地图。

然后将此地图转换为成对数组(带有展开[... ]),然后按该计数对其进行排序( O(nlogn))。

最后,使用.map()

从该数组中再次删除计数

答案 1 :(得分:3)

首先使用数组元素和出现次数创建hash table - 然后对其进行排序。

见下面的演示:

var array = ["Henry","Brian","Henry","Matilda","Henry","Brian","Matthew"];

var hash = array.reduce(function(p,c) {
  p[c] = (p[c] || 0) + 1;
  return p;
},{});

// console.log(hash);

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

console.log(result);

答案 2 :(得分:1)

array.sort((a, b) => 
   array.filter(e => e === b).length -  array.filter(e=> e === a).length  
)

然后,删除重复的项目:

[... new Set(array)]

let array = ["Henry", "Brian", "Henry", "Matilda", "Henry", "Brian", "Matthew"]


array = array.sort((a, b) =>
  array.filter(e => e === b).length - array.filter(e => e === a).length
)

console.log(
  [...new Set(array)]
)

答案 3 :(得分:1)

您可以计算所有项目,然后在计数递减的情况下对键进行排序。

var array = ["Henry", "Brian", "Henry", "Matilda", "Henry", "Brian", "Matthew"],
    count = Object.create(null),
    result;

array.forEach(function (a) {
    count[a] = (count[a] || 0) + 1;
});

result = Object.keys(count).sort(function (a, b) { return count[b] - count[a]; });

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 4 :(得分:0)

我想哈希方法应该是最快的,但这是另一种利用.findIndex()仅在唯一项目中运行的方法,这些项目可能也不会那么糟糕。它只是将唯一的items数组(p)与前一个数组交换,如果它的长度大于前一个。

var data = ["Henry","Brian","Henry","Matilda","Henry","Brian","Matthew","Matthew","John","Matthew"],
  result = data.reduce(function(p,c){
                         var fi = p.findIndex(f => f[0] === c);
                         return fi === -1 ? (p.push([c]), p)
                                          : (p[fi].push(c),
                                             fi ? (p[fi].length > p[fi-1].length && ([p[fi-1],p[fi]] = [p[fi],p[fi-1]]),p)
                                                : p);
                                    },[])
               .map(e => e[0]);
console.log(result);