0

I want to create an array of four numbers from 1-20. I am using Array.from() to do so but I am getting duplicate numbers. How can I ensure I get four unique numbers? This is the code I have so far.

function randomArray() {
  const arr = Array.from(
    { length: 4 },
    (v, i) => Math.floor(Math.random() * 20) + 1
  );
  const arr2 = arr;
  arr2.forEach((val) => {
    if(arr2.includes(val)) {
      arr2.splice(val)
    }
  })
  console.log((arr.filter(moreThenZero)))
}

function moreThenZero(num) {
  return num > 0;
}

The second function was created to filter out 0's produced by array.from(). The + 1 in randomArray() may be redundant but I'm not sure. The forEach was created to avoid the duplicate #'s produced by array.from() but it's not working. Is there any other method I can use?

BizzyBee
  • 9
  • 2
  • create an Array of numbers 1 to 20 ... shuffle ... take top 4 – Jaromanda X Aug 11 '23 at 03:50
  • "*The forEach was created to avoid the duplicate #'s produced by array.from() but it's not working.*" - that's because `arr2` is not a copy, and you're modifying the array while iterating it. Don't do that. – Bergi Aug 11 '23 at 03:51

0 Answers0