简体   繁体   English

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

[英]sort by number of occurrence(count) in Javascript array

I am new to Jquery and Javascript. Can someone please help me with Jquery sorting based on number of occurrence(count) in array.我是 Jquery 和 Javascript 的新手。有人可以帮我根据数组中出现的次数(计数)对 Jquery 进行排序。 I tried various sorting methods but none of them worked.我尝试了各种排序方法,但都没有用。

I have an array in Javascript which is我在 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

I need output like this我需要这样的 output

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

I tried我试过

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
}

output is {4: 2, 2: 6, 6:3} output 是{4: 2, 2: 6, 6:3}

I don't think there's a direct solution in one step and of course it's not just a sort (a sort doesn't remove elements).我不认为一步有直接的解决方案,当然它不仅仅是一种排序(排序不会删除元素)。 A way to do this would be to build an intermediary map of objects to store the counts :一种方法是构建一个中间对象映射来存储计数:

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 });

Note that you don't need jQuery here.请注意,这里不需要 jQuery。 When you don't manipulate the DOM, you rarely need it.当您不操作 DOM 时,您很少需要它。

Just adding my idea as well ( a bit too late )只是添加我的想法(有点太晚了

 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)

I don't think jquery is needed here.我认为这里不需要 jquery。

There are several great answers to this question already, but I have found reliability to be an issue in some browsers (namely Safari 10 -- though there could be others).这个问题已经有几个很好的答案,但我发现可靠性在某些浏览器中是一个问题(即 Safari 10——尽管可能还有其他浏览器)。

A somewhat ugly, but seemingly reliable, way to solve this is as follows:解决这个问题的一个有点丑陋但看似可靠的方法如下:

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())
}

Test测试

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

This is the function i use to do this kind of stuff:这是我用来做这种事情的功能:

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
}
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 objects are collections of values. Set对象是值的集合。 A value in the Set may only occur once; Set中的一个值只能出现一次; it is unique in the Set 's collection.它在Set的集合中是独一无二的。

The singles variable spreads all of the unique values from allTypesArray using the Set object with the spread operator inside of an array. singles变量使用Set对象和数组内部的扩展运算符扩展allTypesArray中的所有唯一值。

The sortedSingles variable sorts the values of the singles array in ascending order by comparing the numbers. sortedSingles变量通过比较数字以升序对singles数组的值进行排序。

Not sure if there's enough neat answers here, this is what I came up with:不确定这里是否有足够简洁的答案,这就是我想出的:

Fill an object with counts for each of the elements:用每个元素的计数填充对象:

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 }
} */

For the values in that new object, sort them by .count, and map() them into a new array (with just the values):对于该新对象中的值,按 .count 对它们进行排序,然后将它们 map() 到一个新数组中(仅包含值):

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

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

Altogether:共:

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);
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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM