Search This Blog

2026/08/09

Javascript : Find Duplicate in array using Object

 



 const arr = [4, 2, 7, 4, 2, 8, 4, 9];
 let duplicates = {};

 for (let i = 0; i < arr.length; i++) {
        if (duplicates[arr[i]]) {
            duplicates[arr[i]] = duplicates[arr[i]] + 1;
        } else {
            duplicates[arr[i]] = 1;
        }
 }

 console.log("Duplicates", duplicates);

 Output:
 Duplicates { '2': 2, '4': 3, '7': 1, '8': 1, '9': 1 }  

 Explanation:
1. We first initialize an empty object called `duplicates` to store the occurrence of each number
2. We then loop through the array and check if the current number is already present in the
`duplicates` object. If it is present, we increment its count by 1. If it is not present,
we add it to the `duplicates` object with a count of 1.

No comments:

Post a Comment