JavaScript で配列内の重複値をカウントする方法 質問する

JavaScript で配列内の重複値をカウントする方法 質問する

現在、次のような配列を取得しました。

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

ベストアンサー1

const counts = {};
const sampleArray = ['a', 'a', 'b', 'c'];
sampleArray.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts)

おすすめ記事