jquery数组中的元素数

时间:2015-12-24 13:43:24

标签: javascript jquery arrays count

我在Jquery中有数组如下,

[125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32]

它有重复。我想要计算数组中的每个元素(关联数组)。

4 个答案:

答案 0 :(得分:1)

尝试以下脚本

var Items = [125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32],
    counts = {};

jQuery.each(Items , function(key,value) {
  if (!counts.hasOwnProperty(value)) {
    counts[value] = 1;
  } else {
    counts[value]++;
  }
});

答案 1 :(得分:1)

使用arry

中的值填充'频率'对象

var frequencies = {};
[125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32].map( 
  function (v) {
    if (frequencies[v]) { frequencies[v] += 1; }
    else { frequencies[v] = 1; }
    return v;
}, frequencies);

var result = document.querySelector('#result');
result.textContent = JSON.stringify(frequencies, 0, 2) +
                     '\nAnd unique \'values\' from the frequencies object:\n[' +
                     Object.keys(frequencies).join(', ') + ']';
<pre id="result"></pre>

答案 2 :(得分:1)

Array.prototype.reduce()

的非常短的版本

var array = [125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32],
    count = array.reduce(function (r, a) {
        r[a] = (r[a] || 0) + 1;
        return r;
    }, {});

document.write('<pre>' + JSON.stringify(count, 0, 4) + '</pre>');

答案 3 :(得分:1)

此解决方案将为您提供每个元素(无论它是什么)的计数,但它不会区分+0-0(SameValueZero)。

&#13;
&#13;
var array = [125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32];
var counts = array.reduce(function(acc, item) {
  if (acc.has(item)) {
    acc.set(item, acc.get(item) + 1);
  } else {
    acc.set(item, 1);
  }
  return acc;
}, new Map());
document.getElementById('out').textContent = JSON.stringify(Array.from(counts), null, 2);
console.log(counts);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.4.1/es5-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.34.0/es6-shim.js"></script>
<pre id="out"></pre>
&#13;
&#13;
&#13;

如果你想要一组唯一值。

&#13;
&#13;
var array = [125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32];
var unique = Array.from(new Set(array));
document.getElementById('out').textContent = JSON.stringify(unique, null, 2);
console.log(unique);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/es5-shim/4.4.1/es5-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/json3/3.3.2/json3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.34.0/es6-shim.js"></script>
<pre id="out"></pre>
&#13;
&#13;
&#13;