JavaScript数组中的唯一计数,按计数排序 [英] Unique counts in JavaScript array, sorted by counts

查看:71
本文介绍了JavaScript数组中的唯一计数,按计数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript名称列表.我想做的是获取唯一名称列表,但是对于该唯一名称列表,还提供了原始列表中有多少个名称的计数.此外,我需要按编号的降序对最终的唯一名称列表进行排序(如果某些名称具有相同的计数,则按名称升序).

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).

这就是我所拥有的,这只是一个简单的字符串列表,然后为我提供了唯一名称列表.从这里,我不确定从何处获取计数或如何按计数对唯一列表进行排序.我认为最终结果将是一个2D的名称和计数数组或2个单独的数组,但是我不确定如何以最好,最有效的方式进行处理.

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);

这篇关于JavaScript数组中的唯一计数,按计数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆