如何在javascript中计算数组中的重复值
2022-08-30 02:26:46
目前,我得到了一个这样的数组:
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,如果你不希望这在较旧的浏览器中中断。