目前,我得到了一个这样的数组:
var uniqueCount = Array();
几步后,我的数组看起来像这样:
uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];
如何计算数组中有多少 a、b、c?我想要这样的结果:
a = 3
b = 1
c = 2
d = 2
等等。
目前,我得到了一个这样的数组:
var uniqueCount = Array();
几步后,我的数组看起来像这样:
uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];
如何计算数组中有多少 a、b、c?我想要这样的结果:
a = 3
b = 1
c = 2
d = 2
等等。
const counts = {};
const sampleArray = ['a', 'a', 'b', 'c'];
sampleArray.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts)
像这样的东西:
uniqueCount = ["a","b","c","d","d","e","a","b","c","f","g","h","h","h","e","a"];
var count = {};
uniqueCount.forEach(function(i) { count[i] = (count[i]||0) + 1;});
console.log(count);
如果您不想在旧浏览器中中断,请使用简单的 for 循环而不是 forEach。
我偶然发现了这个(非常古老的)问题。有趣的是,最明显和优雅的解决方案(恕我直言)不见了:Array.prototype.reduce(...)。自大约 2011 年(IE)或更早(所有其他浏览器)以来,所有主要浏览器都支持此功能:
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:
console.log(map);
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
编辑:
通过在箭头函数中使用逗号运算符,我们可以用一行代码编写它:
var arr = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];
var map = arr.reduce((cnt, cur) => (cnt[cur] = cnt[cur] + 1 || 1, cnt), {});
// map is an associative array mapping the elements to their frequency:
console.log(map);
// prints {"a": 3, "b": 2, "c": 2, "d": 2, "e": 2, "f": 1, "g": 1, "h": 3}
但是,由于这可能更难阅读/理解,因此您可能应该坚持使用第一个版本。
function count() {
array_elements = ["a", "b", "c", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
array_elements.sort();
var current = null;
var cnt = 0;
for (var i = 0; i < array_elements.length; i++) {
if (array_elements[i] != current) {
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times<br>');
}
current = array_elements[i];
cnt = 1;
} else {
cnt++;
}
}
if (cnt > 0) {
document.write(current + ' comes --> ' + cnt + ' times');
}
}
count();
您也可以使用高阶函数来进行运算。 看到这个答案
简单更好,一个变量,一个函数:)
const arr = ["a", "b", "c", "d", "d", "e", "a", "b", "c", "f", "g", "h", "h", "h", "e", "a"];
const counts = arr.reduce((acc, value) => ({
...acc,
[value]: (acc[value] || 0) + 1
}), {});
console.log(counts);