【问题标题】:sort by number of occurrence(count) in Javascript array按 Javascript 数组中的出现次数(计数)排序
【发布时间】:2014-02-25 09:57:24
【问题描述】:

我是 Jquery 和 Javascript 的新手。有人可以根据数组中的出现次数(计数)帮助我进行 Jquery 排序。我尝试了各种排序方法,但都没有奏效。

我在 Javascript 中有一个数组

allTypesArray = ["4", "4","2", "2", "2", "6", "2", "6", "6"]

// here  2 is printed four times, 6 is printed thrice, and 4 is printed twice

我需要这样的输出

newTypesArray = ["2","6","4"]

我试过了

function array_count_values(e) {
var t = {}, n = "",
    r = "";
var i = function (e) {
    var t = typeof e;
    t = t.toLowerCase();
    if (t === "object") {
        t = "array"
    }
    return t
};
var s = function (e) {
    switch (typeof e) {
    case "number":
        if (Math.floor(e) !== e) {
            return
        };
    case "string":
        if (e in this && this.hasOwnProperty(e)) {
            ++this[e]
        } else {
            this[e] = 1
        }
    }
};
r = i(e);
if (r === "array") {
    for (n in e) {
        if (e.hasOwnProperty(n)) {
            s.call(t, e[n])
        }
    }
}
return t
}
6: 3
}

输出是 {4: 2, 2: 6, 6:3}

【问题讨论】:

  • 你能告诉我们你的代码吗?
  • 这些不同的方法是什么?他们是怎么不工作的?
  • 我希望下面的帖子可以帮助你实现同样的目标.. stackoverflow.com/questions/19464440/…
  • 那不是排序(因为你改变了数组的内容
  • @GabyakaG.Petrioli,是的,它按每个元素的出现次数排序。

标签: javascript jquery arrays sorting


【解决方案1】:

我不认为一步有直接的解决方案,当然它不仅仅是一种排序(排序不会删除元素)。一种方法是构建一个中间对象映射来存储计数:

var allTypesArray = ["4", "4","2", "2", "2", "6", "2", "6", "6"];
var s = allTypesArray.reduce(function(m,v){
  m[v] = (m[v]||0)+1; return m;
}, {}); // builds {2: 4, 4: 2, 6: 3} 
var a = [];
for (k in s) a.push({k:k,n:s[k]});
// now we have [{"k":"2","n":4},{"k":"4","n":2},{"k":"6","n":3}] 
a.sort(function(a,b){ return b.n-a.n });
a = a.map(function(a) { return a.k });

请注意,这里不需要 jQuery。当您不操作 DOM 时,您很少需要它。

【讨论】:

  • FWIW 你可以保存几个字符return m[v] = ++m[v]||0, m
  • 谢谢。你救了我。 :)
  • @elclanrs 看起来我在打高尔夫球吗? ^^
【解决方案2】:

也加入我的想法(有点太晚了

var allTypesArray = ["4", "4", "2", "2", "2", "6", "2", "6", "6"];
var map = allTypesArray.reduce(function(p, c) {
  p[c] = (p[c] || 0) + 1;
  return p;
}, {});

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

console.log(newTypesArray)

【讨论】:

    【解决方案3】:

    我认为这里不需要 jquery。

    这个问题已经有几个很好的答案,但我发现可靠性在某些浏览器中是一个问题(即 Safari 10——尽管可能还有其他浏览器)。

    一个有点丑陋但看似可靠的解决方法如下:

    function uniqueCountPreserve(inputArray){
        //Sorts the input array by the number of time
        //each element appears (largest to smallest)
    
        //Count the number of times each item
        //in the array occurs and save the counts to an object
        var arrayItemCounts = {};
        for (var i in inputArray){
            if (!(arrayItemCounts.hasOwnProperty(inputArray[i]))){
                arrayItemCounts[inputArray[i]] = 1
            } else {
                arrayItemCounts[inputArray[i]] += 1
            }
        }
    
        //Sort the keys by value (smallest to largest)
        //please see Markus R's answer at: http://stackoverflow.com/a/16794116/4898004
        var keysByCount = Object.keys(arrayItemCounts).sort(function(a, b){
            return arrayItemCounts[a]-arrayItemCounts[b];
        });
    
        //Reverse the Array and Return
        return(keysByCount.reverse())
    }
    

    测试

    uniqueCountPreserve(allTypesArray)
    //["2", "6", "4"]
    

    【讨论】:

      【解决方案4】:

      这是我用来做这类事情的函数:

      function orderArr(obj){
          const tagsArr = Object.keys(obj)
          const countArr = Object.values(obj).sort((a,b)=> b-a)
        const orderedArr = []
        countArr.forEach((count)=>{
          tagsArr.forEach((tag)=>{
              if(obj[tag] == count && !orderedArr.includes(tag)){
              orderedArr.push(tag)
            }
          })
        })
        return orderedArr
      }
      

      【讨论】:

        【解决方案5】:
        const allTypesArray = ["4", "4","2", "2", "2", "6", "2", "6", "6"]
        
        const singles = [...new Set(allTypesArray)]
        const sortedSingles = singles.sort((a,b) => a - b)
        console.log(sortedSingles)
        

        Set 对象是值的集合。 Set 中的一个值只能出现一次;它在Set 的收藏中是独一无二的。

        singles 变量使用 Set 对象和数组内部的扩展运算符扩展来自 allTypesArray 的所有唯一值。

        sortedSingles 变量通过比较数字对singles 数组的值进行升序排序。

        【讨论】:

        • OP 想要根据每个值在原始数组中出现的数量进行排序。
        猜你喜欢
        • 1970-01-01
        • 2011-05-16
        • 1970-01-01
        • 1970-01-01
        • 2014-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多