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.
Here, the includes() function checks if an element is present in the array or not.
Example:
JavaScript
const n = 5
const arr = [];
if (n == 0) {
console.log( null )
}
do {
const randomNumber = Math
.floor(Math.random() * 100) + 1
if (!arr.includes(randomNumber)) {
arr.push(randomNumber);
}
}
while (arr.length < n);
console.log(arr)
|
Output
[ 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
const n = 5
const arr = [];
if (n == 0) {
console.log( null )
}
let randomnumbers = new Set, ans;
while (randomnumbers.size < n) {
randomnumbers.add(Math.floor(
Math.random() * 100) + 1);
}
ans = [...randomnumbers];
console.log(ans)
|
Output
[ 41, 75, 57, 62, 92 ]
Time complexity:
O(n)
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Jul, 2023
Like Article
Save Article