English 中文(简体)
如何在一个阵列中找到重复数字, 并使用 javascript 来递增重复值 [关闭]
原标题:how to find duplicate number in an array and increment the duplicate value using javascript [closed]
  • 时间:2024-05-21 11:01:33
  •  标签:
Closed. This question needs debugging details. It is not currently accepting answers. Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question. Closed last month. This post was edited and submitted for review 1 hour ago. Improve this question 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 : 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] const array = [1,2,3,4,4,5,6,7,8,8,9,10]; const duplicates = array.filter((item, index) => array.indexOf(item) !== index); console.log(duplicates); // Output: [2, 4, 5]
最佳回答
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);
问题回答

暂无回答




相关问题
热门标签