How to use do-while loop and includes() Method In Javascript

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)


Output

[ 29, 36, 38, 83, 50 ]

Time complexity: 

O(n2)

How to create an array containing non-repeating elements in JavaScript ?

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.

Similar Reads

Method 1: Using do-while loop and includes() Method

Here, the includes() function checks if an element is present in the array or not....

Method 2: Using a set and checking its size

...