In this article, we will learn how to create an array containing non-repeating elements in JavaScript.
The following are the two approaches to generate an array containing n number of non-repeating random numbers.
- Using do-while loop and includes() Method.
- Using a set and checking its size
Method 1: Using do-while loop and includes() Method
Here, the includes() function checks if an element is present in the array or not.
Example:
JavaScript
// You can take this value from user const n = 5 Â
// Initial empty array const arr = []; Â
// Null check if (n == 0) { Â Â Â Â console.log( null ) } Â
do {     // Generating random number     const randomNumber = Math         .floor(Math.random() * 100) + 1 Â
    // Pushing into the array only     // if the array does not contain it     if (!arr.includes(randomNumber)) {         arr.push(randomNumber);     } } while (arr.length < n); Â
// Printing the array elements console.log(arr) |
[ 29, 36, 38, 83, 50 ]
Time complexity:Â
O(n2)
Method 2: Using a set and checking its size
Remember that a set does not allow duplicate elements.
Example:
JavaScript
// You can take this value from user const n = 5 Â
// Initial empty array const arr = []; Â
// Null Check if (n == 0) { Â Â Â Â console.log( null ) } Â
let randomnumbers = new Set, ans; Â
// We keep adding elements till // size of set is equal to n while (randomnumbers.size < n) { Â
    // Generating random number     // and adding it     randomnumbers.add(Math.floor(         Math.random() * 100) + 1); } Â
// Copying set elements into // the result array ans = [...randomnumbers]; Â
// Printing the array console.log(ans) |
[ 41, 75, 57, 62, 92 ]
Time complexity:
O(n)