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

7y4bm7vi  于 2022-12-03  发布在  jQuery
关注(0)|答案(7)|浏览(174)

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

qpgpyjmq

qpgpyjmq1#

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

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

nle07wnf

nle07wnf2#

只是添加我的想法以及(* 有点太晚了 *)

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)
8yparm6h

8yparm6h3#

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

3ks5zfa04#

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

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
}
wnvonmuf

wnvonmuf5#

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对象,在数组内使用spread运算子,来分摊allTypesArray中的所有唯一值。
sortedSingles变量通过比较数字按升序对singles数组得值进行排序.

des4xlb0

des4xlb06#

我不确定这里是否有足够简洁的答案,这是我想到的:
使用每个元素的计数填充对象:

let array = ['4', '4', '2', '2', '2', '6', '2', '6', '6'];
let arrayCounts = {}

for (j in array) arrayCounts[array[j]] ? arrayCounts[array[j]].count++ : arrayCounts[array[j]] = { val: array[j], count: 1 };

/* arrayCounts = {
  '2': { val: '2', count: 4 },
  '6': { val: '4', count: 2 },
  '4': { val: '6', count: 3 }
} */

对于该新对象中的值,按.count对其进行排序,并将其map()到一个新数组中(仅包含值):

let sortedArray = Object.values(arrayCounts).sort(function(a,b) { return b.count - a.count }).map(({ val }) => val);

/* sortedArray = [ '2', '6', '4' ] */

总计:

let arrayCounts = {}

for (j in array) arrayCounts[array[j]] ? arrayCounts[array[j]].count++ : arrayCounts[array[j]] = { val: array[j], count: 1 };
    
let sortedArray = Object.values(arrayCounts)
    .sort(function(a,b) { return b.count - a.count })
    .map(({ val }); => val);
liwlm1x9

liwlm1x97#

var number = [22,44,55,11,33,99,77,88];

   for(var i = 0;i<number.length;i++) {
   for(var j=0;j<number.length;j++){
         if(number[j]>number[j+1]){
                 var primary =number[j];
                 number[j] =  number[j+1];
                 number[j+1] =primary;
             }
         }
    }document.write(number);

相关问题