ArticleZip > How To Count Duplicate Value In An Array In Javascript

How To Count Duplicate Value In An Array In Javascript

When working on projects in JavaScript, you may encounter situations where you need to find and count duplicate values in an array. This task might seem tricky at first, but fear not! With a few simple steps, you can easily identify and tally duplicate values in your array.

To start, let's break down the process into manageable steps. The fundamental approach involves iterating through the array, keeping track of each unique value and its occurrence count.

One efficient way to accomplish this is by using an object to store the count of each unique element. Let's dive into the code:

Javascript

function countDuplicates(arr) {
    let countMap = {};
    let duplicates = {};

    arr.forEach(item => {
        if (countMap[item]) {
            countMap[item]++;
            duplicates[item] = countMap[item];
        } else {
            countMap[item] = 1;
        }
    });

    return duplicates;
}

// Example usage
const array = [1, 2, 3, 4, 2, 5, 3, 6, 2];
const duplicateCounts = countDuplicates(array);
console.log(duplicateCounts);

In the code snippet above, we define a `countDuplicates` function that takes an array as input. Inside the function, we create a `countMap` object to keep track of the count of each element in the array. We also initialize a `duplicates` object to store the duplicate values along with their counts.

By iterating through the array using `forEach`, we check if the element is already present in the `countMap`. If it is, we increment the count and store the value in the `duplicates` object. If the element is encountered for the first time, we set its count to 1 in the `countMap`.

Once the iteration is complete, the `countDuplicates` function returns the `duplicates` object containing the duplicate values and their respective counts.

When you run the provided code with the `array` example, you will get an output showing the duplicate values and their counts, making it easy to identify and manage duplicate elements in your array.

By following this straightforward approach, you can efficiently count duplicate values in an array using JavaScript. Remember, this method leverages the power of objects to simplify the process and provide a clear overview of duplicate occurrences in your data.

Next time you encounter duplicate values in an array within your JavaScript projects, you now have a reliable method at your disposal to handle them effectively. Happy coding!