Question
I have an array to find the duplicate value and their Index also
const arr = [10, 5, 8, 8, 5, 10, 6, 5, 2, 3]
Answer
const arr = [10, 5, 8, 8, 5, 10, 6, 5, 2, 3];
const duplicates = {};
for (let i = 0; i < arr.length; i++) {
const num = arr[i];
// Check if the number is already in the duplicates object
if (duplicates[num]) {
// Add the current index to the list of indices
duplicates[num].push(i);
} else {
// Initialize with the current index
duplicates[num] = [i];
}
}
// Filter out numbers with only one occurrence
const result = Object.entries(duplicates)
.filter(([key, indices]) => indices.length > 1)
.reduce((acc, [key, indices]) => {
acc[key] = indices;
return acc;
}, {});
console.log(result);
Explanation
The duplicates
object maps each number to an array of its indices.As the for
loop iterates through arr
, it checks if the number is already in duplicates
:
- If it is, the current index is added to the list.
- If it isn’t, a new array is created with the current index.
After populating duplicates
, Object.entries
is used to filter out numbers with only one occurrence, leaving only duplicates and their indices.