Skip to content
Related Articles

Related Articles

How to create an array containing non-repeating elements in JavaScript ?
  • Last Updated : 30 Nov, 2020

The following are the two approaches to generate an array containing n number of non-repeating random numbers.

  1. Using do-while loop and includes() function.
  2. Using a set and checking with its size.

Using do-while loop and includes() function: Here, includes() function checks if an element is present in the array or not.

Filename: index.js

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)

Run the index.js file using the following command:



node index.js

Output:

[ 49, 99, 27, 86, 69 ]

Time complexity: 

O(n2)

Using a set and checking with its size: Remember that a set does not allow duplicate elements.

Filename: index.js

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)

Run the index.js file using the following command:

node index.js

Output:

[ 52, 32, 50, 59, 95 ]

Time complexity:

O(n)
My Personal Notes arrow_drop_up
Recommended Articles
Page :