Currently, I got an array like that:
var uniqueCount = Array();
After a few steps, my array looks like that:
uniqueCount =
var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
Single line based on reduce array function
const uniqueCount = ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
const distribution = uniqueCount.reduce((acum,cur) => Object.assign(acum,{[cur]: (acum[cur] || 0)+1}),{});
console.log(JSON.stringify(distribution,null,2));
You can have an object that contains counts. Walk over the list and increment the count for each element:
var counts = {};
uniqueCount.forEach(function(element) {
counts[element] = (counts[element] || 0) + 1;
});
for (var element in counts) {
console.log(element + ' = ' + counts[element]);
}
You can solve it without using any for/while loops ou forEach.
function myCounter(inputWords) {
return inputWords.reduce( (countWords, word) => {
countWords[word] = ++countWords[word] || 1;
return countWords;
}, {});
}
Hope it helps you!
I stumbled across this (very old) question. Interestingly the most obvious and elegant solution (imho) is missing: Array.prototype.reduce(...). All major browsers support this feature since about 2011 (IE) or even earlier (all others):
var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce(function(prev, cur) {
prev[cur] = (prev[cur] || 0) + 1;
return prev;
}, {});
// map is an associative array mapping the elements to their frequency:
document.write(JSON.stringify(map));
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
Quickest way:
Сomputational complexity is O(n).
function howMuchIsRepeated_es5(arr) {
const count = {};
for (let i = 0; i < arr.length; i++) {
const val = arr[i];
if (val in count) {
count[val] = count[val] + 1;
} else {
count[val] = 1;
}
}
for (let key in count) {
console.log("Value " + key + " is repeated " + count[key] + " times");
}
}
howMuchIsRepeated_es5(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);
The shortest code:
Use ES6.
function howMuchIsRepeated_es6(arr) {
// count is [ [valX, count], [valY, count], [valZ, count]... ];
const count = [...new Set(arr)].map(val => [val, arr.join("").split(val).length - 1]);
for (let i = 0; i < count.length; i++) {
console.log(`Value ${count[i][0]} is repeated ${count[i][1]} times`);
}
}
howMuchIsRepeated_es6(['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a']);