开发者

Iterate through an array and return how many of each is present in jquery

开发者 https://www.devze.com 2023-02-26 20:23 出处:网络
So I have an array. The array has string values inside that can change each time: var array = [\'1\',\'2\',\'3\',\'4\',\'5\'];

So I have an array. The array has string values inside that can change each time:

var array = ['1','2','3','4','5'];

or sometimes:

var array = ['1','4','3','4','4'];

or even:

var array = ['1','3','3','4','4'];

How would I go about iterating through this array, figuring out which value is present the most and then displaying it. Also, how would I go about making it even smarter to understand that sometimes there is a tie between two values, as is the case in the las开发者_高级运维t array above, and then displaying info notifying me that values "3" and "4" are tied... Or if there is no value that occurs more than once, thus displaying all values. Thoughts?


function findMostFrequent(array) {
    // {
    //    "valueInTheArray": numberOfOccurances,
    //    ...
    // }
    var data = {};
    // for each value in the array increment the number of 
    // occurences for that value. the or clause defaults it to 0.
    $.each(array, function(i, val) {
        data[val] = data[val]++ || 1;
    });
    var answer = null;
    // for each value if the occurances is higher then to the counter.
    // then set that as the counter.
    $.each(data, function(key, val) {
         if (val > data[answer]) answer = key;
    }
    return answer;
}

You need two loops. One to count how many times each value occured. And one to find which one occured the most.

Optionally if you want to handle multiple high values then replace the second loop with this.

var answer = [null];
// for each value if the occurances is equal then add it to the array
// else if the occurance is higher then the current highest occurance.
// then set that as the current array of values.
$.each(data, function(key, val) {
     if (val === data[answer[0]]) {
          answer.push(key);
     } else if (val > data[answer[0]]) {
          answer = [key];
     }
}
return answer;


Try this:

var array = ['1','2','3', '3','4','5', '3', '4', '5', '5'],
l = array.length,
col = {},
current,
max = {cnt:0, values:[]};
while(l--){
  current = array[l];
  col[current] = (col[current] || 0) + 1;
  if(col[current] > max.cnt){
    max = {cnt:col[current], values: [current]};
  }else if(col[current] === max.cnt){
    max.values.push(current);
  }
}
console.log(
  max.cnt === 1 ? 
    'they are all different' : 
    max.values.join(',') + ' occured ' + max.cnt + ' times'
);


You probably want to use something like this:

var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
var counts = {};

for(var i = 0; i< arr.length; i++) {
    var num = arr[i];
    counts[num] = counts[num] ? counts[num]+1 : 1;
}

Now, you'll have an object that has a count of all the members in the array.

console.log(counts[5]); // logs '3'
0

精彩评论

暂无评论...
验证码 换一张
取 消