由最高计数的JQuery的Javascript数组排序 [英] JQuery Javascript Sort Array by Highest Count

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

问题描述

我有:

myArray = ["ABAB", "ABAB", "ABAB", "CDCD", "EFEF", "EFEF"]

我需要通过事件和排序最高的数来算。这将是回报率:

I need to count by occurrences and sort by highest count. This would be the return:

ABAB 3
EFEF 2
CDCD 1

请注意,在数组中的参数由grepping每个静态或文字文本模式将不利于也在不断改变,因此

Note, the parameters inside the array are constantly changed so by "grepping" for each static or literal text pattern won't help.

的最快方法任何想法要么使用jQuery或纯JS做到这一点?

Any idea of the fastest way to accomplish this either with JQuery or plain JS?

推荐答案

第一步:建立直方图,作为地图元素 - >其速度频率(假定所有元素都是字符串):

Step one: build the histogram, as a map element -> its frequency for speed (assumes all elements are strings):

var histogramMap = {};
for(var i=0, len=myArray.length; i<len; i++){
  var key = myArray[i];
  histogramMap[key] = (histogramMap[key] || 0) + 1;
}

第二步:转换为输出对象的数组:

Step two: convert to an array of output objects:

var histogram = [];
for(key in histogramMap) histogram.push({key: key, freq: histogramMap[key]});

第三步:排序的直方图

Step three: sort the histogram

histogram.sort(function(a,b){return b.freq - a.freq})


这还假定的Object.prototype 不会被修改。这是一个安全的假设作出,以及大量的(我认为)库,包括jQuery的,做这样的假设。但是,如果你决定要枚举的属性添加到的Object.prototype ,这些将被的for..in 回升。如果你想成为安全,修改第二步:


This also assumes that Object.prototype is not modified. This is a safe assumption to make, and lots (I think) of libraries, including jQuery, make that assumption. But, if you decide to add enumerable properties to Object.prototype, these will be picked up by for..in. If you want to be safe, modify the second step to:

var histogram = [];
for(key in histogramMap){
  if(histogramMap.hasOwnProperty(i)){
    histogram.push({key: key, freq: histogramMap[key]});
  }
}

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

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