Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace duplicates with new numbers

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;
}
like image 898
zana10 Avatar asked Mar 01 '23 23:03

zana10


1 Answers

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)
like image 166
charlietfl Avatar answered Mar 05 '23 19:03

charlietfl