Javascript 用新号码替换重复的号码
我希望在不更改数组长度的情况下从数组中删除重复项。如果有重复,我想在索引上生成一个新的随机数。然而,因为这个数字可能已经存在,我需要再次生成它,直到它成为唯一的数字Javascript 用新号码替换重复的号码,javascript,arrays,duplicates,Javascript,Arrays,Duplicates,我希望在不更改数组长度的情况下从数组中删除重复项。如果有重复,我想在索引上生成一个新的随机数。然而,因为这个数字可能已经存在,我需要再次生成它,直到它成为唯一的数字 var-arr=[5,5,5,4,4]; 设计数器=0; for(设i=0;i项目===数字)。长度>1; 设arr=[5,5,5,4,4]; for(设i=0;i-1) { newValue=Math.floor(Math.random()*10) } arr[i]=新值; 我++ } } 返回arr } //这就是我测试的方式,
var-arr=[5,5,5,4,4];
设计数器=0;
for(设i=0;i
使用while
循环而不是if
语句不断检查值,直到它不等于上一个值
不过,在将数字更改为随机数之后,您需要添加额外的检查,以查看该随机数是否已不在数组中
const hasDuplicateNumbers=(数字,数字)=>
数字。过滤器(项目=>项目===数字)。长度>1;
设arr=[5,5,5,4,4];
for(设i=0;i这是解决方案:
var arr = [5, 5, 5, 4, 4];
const replaceduplicates=(arr)=>{
let i =1;
while(i < arr.length -1 ){
const currentElement=arr[i]
const indexOfcurrentElement= arr.indexOf(currentElement)
if(indexOfcurrentElement > -1) {
let newValue=Math.floor(Math.random() * 10 + arr[i-1])
while( arr.indexOf(newValue) > -1)
{
newValue=Math.floor(Math.random() * 10 )
}
arr[i] = newValue;
i++
}
}
return arr
}
//this is how I tested basically this will run for ever
let found=false
while(!found ){
const arrResponse =replaceduplicates(arr)
for (let i = 0; i < arrResponse.length; i++) {
for (let j = i+1; j < arrResponse.length; j++) {
if(arrResponse[i] == arrResponse[j]) found = true
}
}
console.log('no duplicates')
}
var-arr=[5,5,5,4,4];
常量替换重复项=(arr)=>{
设i=1;
而(i-1){
设newValue=Math.floor(Math.random()*10+arr[i-1])
while(arr.indexOf(newValue)>-1)
{
newValue=Math.floor(Math.random()*10)
}
arr[i]=新值;
我++
}
}
返回arr
}
//这就是我测试的方式,基本上这将永远运行
设为假
而(!found){
const arrResponse=replaceduplicates(arr)
for(设i=0;i
以前的元素包含当前索引之前的arr元素,其他元素包含除当前索引之外的所有其他arr元素。如果已经存在实例,则会生成一个新的随机数。然后将新的随机数与arr的所有其余元素进行比较,以避免更改数字的第一个实例。在提供的示例中,索引3将始终保持为4
var arr = [5, 5, 5, 4, 4];
for (let i = 0; i < arr.length; i++) {
let previousElements = arr.slice(0, i);
let otherElements = JSON.parse(JSON.stringify(arr));
otherElements.splice(3, 1);
if (previousElements.includes(arr[i])) {
arr[i] = Math.floor(Math.random() * 10);
while (otherElements.includes(arr[i])) {
arr[i] = Math.floor(Math.random() * 10);
}
}
}
console.log('arr: ' + JSON.stringify(arr));
var-arr=[5,5,5,4,4];
for(设i=0;i
样本输出:[5,8,2,4,3]
示例输出:[5,0,1,4,8]使用集合、数组或对象跟踪已看到的值,使用while循环获取新的唯一值
const arr=[5,5,5,4,4];
const seen=new Set();//仅保留唯一值,即使添加重复项也是如此
arr.forEach((n,i)=>{
while(见has(n)){
arr[i]=n=Math.floor(Math.random()*10);
}
见。添加(n);
});
console.log(arr)
创建一个数字数组,然后洗牌,然后用pop()唯一的随机数来填补你的漏洞。这能回答你的问题吗?