I'm having array in Jquery like following,
[125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32]
It's having duplicate. I want count of each and every element in array(associative array).
I'm having array in Jquery like following,
[125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32]
It's having duplicate. I want count of each and every element in array(associative array).
Try following Script
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]++;
}
});
Populate a 'frequencies' object using values from the 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>
A very short version with 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>');
This solution will give you a count of every element (whatever it is), except it will not differentiate between +0
and -0
(SameValueZero).
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);
<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>
And if you want an array of the unique values.
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);
<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>