Counting Duplicate Elements in an Array in JavaScript
In JavaScript, you may encounter situations where you need to determine the occurrence count of duplicate elements within an array. This is particularly useful for tasks such as data cleaning, analysis, and filtering.
Suppose you have an array called uniqueCount with values [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a]. Your goal is to count the number of occurrences for each unique value in the array.
To achieve this, you can leverage the following code snippet:
const counts = {}; const sampleArray = ['a', 'a', 'b', 'c']; sampleArray.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; }); console.log(counts);
This code iterates through the array using the forEach method. For each element x, it checks if the counts object has a key for that element. If not, it creates a key with a value of 0.
The counts[x] || 0 syntax ensures that the value associated with the element is initialized to 0 if it doesn't exist, effectively avoiding potential errors.
The increment operator (counts[x] || 0) 1 adds 1 to the count for the respective element.
When the loop completes, the counts object contains the count of each unique element in the original array. Console logging counts will display the result:
{ a: 3, b: 1, c: 2, d: 2, e: 2, f: 1, g: 1, h: 3 }
In this example, the array contains three instances of 'a', one instance of 'b', two instances of 'c', two instances of 'd', two instances of 'e', one instance of 'f', one instance of 'g', and three instances of 'h'.
The above is the detailed content of How to Count Duplicate Elements in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!