gpt4 book ai didi

javascript - 用新号码替换重复项

转载 作者:行者123 更新时间:2023-12-03 06:59:29 26 4
gpt4 key购买 nike

我想从数组中删除重复项而不更改其长度。如果有重复,我想在该索引上生成一个新的随机数。但是,因为该号码可能已经存在,所以我需要再次生成它,直到它成为唯一号码。

var arr = [5, 5, 5, 4, 4];
let counter = 0;
for (let i = 0; i < arr.Length; i++) {
for (let j = i + 1; j < arr.Length; j++) {
if (arr[i] === arr[j]) {
arr[j] = Math.floor(Math.random() * 10);
counter++;
}
}
counter = 0;
}

最佳答案

使用 Set 或数组或对象来跟踪已经看到的值,并使用 while 循环来获取新的唯一值

const arr = [5, 5, 5, 4, 4];
const seen = new Set();// only holds unique values, even when add duplicates

arr.forEach((n,i) => {
while(seen.has(n)){
arr[i] = n = Math.floor(Math.random() * 10);
}
seen.add(n);
});

console.log(arr)

关于javascript - 用新号码替换重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64528173/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com