2011-04-19 114 views
0

所以我有一个数组。该阵列具有字符串值内,可每一​​次改变:迭代通过一个数组,并返回每个jQuery中存在多少个

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

或有时:

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

甚至:

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

我怎么会去通过这个数组迭代,盘算取出哪个值出现最多然后显示它。另外,我会如何让它变得更聪明,以便了解有时两个值之间存在联系(如上面最后一个数组中的情况),然后显示通知我值“3”和“4”相关的信息是绑定的...或者如果没有多次出现的值,则显示所有值。思考?

+0

你想从阵列中除了获得出现最值删除重复? – Eli 2011-04-19 18:52:40

+0

不,不删除,只是搜索数组,并找出每个值的总量。 – Jim 2011-04-19 18:55:35

+0

这是某种功课吗? - ) – Mic 2011-04-19 19:19:36

回答

0

试试这个:

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' 
); 
+0

谢谢!这种方法似乎工作得最好。如果两个值等于两个不同的变量,是否有办法将这两个值分开? – Jim 2011-04-19 20:05:41

+0

'max.values [0]',...'max.values [n]'不好? – Mic 2011-04-19 20:20:44

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

您需要两个循环。一个来计算每个值的发生次数。并找到哪一个发生最多。

(可选)如果要处理多个高值,则用此替换第二个循环。

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; 
+0

@GaryGreen数据是一个“对象”而不是“数组”。 – Raynos 2011-04-19 19:07:31

+0

哦哎呀! ;-) – 2011-04-19 19:11:07

+0

谢谢,这一个工作得很好,另一个似乎表现更好。我感谢大家对此的反馈! – Jim 2011-04-19 20:11:19

0

你可能想使用这样的:现在

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

,你必须具有阵列中的所有成员的计数的对象。

console.log(counts[5]); // logs '3' 
相关问题