Frontend Javascript

Frontend Interview Question And Answers

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.

Related Posts

Difference Between Promise and Async Await in Javascript

Promises A promise is an object which represents the eventual completion either rejection of an asynchronous operation. Promise has methods like .then(), .catch(), and finally () to handle…

Leave a Reply

Your email address will not be published. Required fields are marked *