JavaScript数组中的唯一计数,按计数排序

编程入门 行业动态 更新时间:2024-10-24 17:18:45
本文介绍了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数组中的唯一计数,按计数排序

本文发布于:2023-10-30 19:06:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1543729.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组中   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!