How to find duplicate number in an array and increment the duplicate value using javascript.
I have an array with duplicate numbers in it. I need to find the duplicate value and increment the duplicate value and so on.
Input :
var array = [1,2,3,4,4,5,6,7,8,8,9,10];
Expected Result:
array = [1,2,3,4,5,6,7,8,9,10,11,12]
1
function incrementDuplicates(array) {
const seen = new Set();
for (let i = 0; i < array.length; i++) {
while (seen.has(array[i])) {
array[i]++;
}
seen.add(array[i]);
}
return array;
}
var array = [1, 2, 3, 4, 4, 5, 6, 7, 8, 8, 9, 10];
array = incrementDuplicates(array);
console.log(array);