I want to remove duplicates from an array without changing its length. If there is a duplicate, I want to generate a new random number on that index. However because that number could already exists, I need to generate it again until it becomes a unique number.
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;
}
Use a Set or array or object to keep track of the values already seen and a while loop to get new unique value
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With