如何在一个阵列中找到重复数字, 并使用 javascript 来递增重复值 [关闭]
原标题:how to find duplicate number in an array and increment the duplicate value using javascript [closed]
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);
问题回答
暂无回答
相关问题
热门标签
- winforms
- combobox
- fogbugz
- java
- date
- internationalization
- asp.net
- iis
- url-rewriting
- urlrewriter
- c#
- enums
- ocaml
- haxe
- algorithm
- string
- viewstate
- .net
- c++
- c
- symbol-table
- mysql
- database
- postgresql
- licensing
- migration
- vb.net
- vb6
- declaration
- vb6-migration
- python
- psycopg2
- backup
- vmware
- virtualization
- gnu-screen
- authentication
- desktop
- excel
- xll
- cultureinfo
- regioninfo
- oracle
- client
- session
- download
- html
- virtual
- constructor
- scenarios
- perl
- full-text-search
- javascript
- ajax
- testing
- oop
- inheritance
- vim
- encapsulation
- information-hiding