Counting Duplicate Values in an Array in JavaScript
One of the common operations you might need to perform while working with arrays in JavaScript is counting the number of times each element appears. This can be useful for various scenarios, such as analyzing data or finding the most frequent values.
Consider an array that initially contains unique values:
var uniqueCount = ['a', 'b', 'c', 'd'];
After some operations, the array might have duplicate values:
uniqueCount = ['a', 'b', 'c', 'd', 'd', 'e', 'a', 'b', 'c', 'f'];
To count the number of occurrences of each value in this array, you can use a simple approach.
Create an empty object called counts:
const counts = {};
Iterate through each element in the original array:
sampleArray.forEach(function (x) {
Inside the loop, check if the element exists as a key in the counts object. If it doesn't, initialize its count to 0. If it does, increment the count.
counts[x] = (counts[x] || 0) + 1;
After iterating through all elements, the counts object will contain the count for each unique value in the original array.
console.log(counts);
Expected output:
{ a: 3, b: 2, c: 2, d: 2, e: 1, f: 1 }
This approach allows you to efficiently count duplicate values in an array, enabling you to perform further analysis or operations based on the frequency of elements.
The above is the detailed content of How Can I Count Duplicate Values in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!