按Javascript数组中的出现次数(计数)排序

时间:2014-02-25 09:57:24

标签: javascript jquery arrays sorting

我是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}

5 个答案:

答案 0 :(得分:6)

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

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时,你很少需要它。

答案 1 :(得分: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[a] < map[b];
});

答案 2 :(得分:2)

我认为这里不需要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"]

答案 3 :(得分:0)

这是我用来做这种事情的功能:

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
}

答案 4 :(得分:0)

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 变量使用 allTypesArray 对象和数组内的扩展运算符扩展 Set 中的所有唯一值。

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