Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generate numbers from 1 to 100 in an array in a way no number is repeated

How do I generate numbers from 1 to 100 in an array without actually typing every single number from 1 to 100 in a way that each number appears only once. I later need to move the generated numbers to an different array but I have that part figured out.
Here is what I have done so far

const arr1 = [1,2,3,4,5,6]
const arr2 = []

const ran = () => {
  const index = Math.floor(Math.random() * arr1.length);
  if(arr1.length>0)
  {
    arr2.push(arr1[index])
    arr1.splice(index, 1)
    
    const display = document.getElementById('array')
    display.innerText = ("\nArray 2 elements " + arr2.toString() + "\n Remaining Array 1 elements" + arr1.toString())
  }
  else
    {
      document.write("Array is now empty");
    }
}
<button onClick=ran()>click</button>
<span id='array' />

In the above snippet I have displayed elements in array1 as well but I don’t need to do it if the numbers are from 1 to 100

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you can use map

const array = Array(100).fill(1).map((n, i) => n + i)

console.log(array)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading