How to create an array containing non-repeating elements in JavaScript ? Improve Improve Improve Like Article Like Save Article Save Share Report issue Report 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 sizeMethod 1: Using do-while loop and includes() MethodHere, the includes() function checks if an element is present in the array or not. Example: JavaScript // You can take this value from userconst n = 5 // Initial empty arrayconst arr = []; // Null checkif (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 elementsconsole.log(arr) Output[ 29, 36, 38, 83, 50 ] Time complexity: O(n2)Method 2: Using a set and checking its sizeRemember that a set does not allow duplicate elements. Example: JavaScript // You can take this value from userconst n = 5 // Initial empty arrayconst arr = []; // Null Checkif (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 arrayans = [...randomnumbers]; // Printing the arrayconsole.log(ans) Output[ 41, 75, 57, 62, 92 ] Time complexity: O(n) Last Updated : 11 Jul, 2023 Like Article Save Article Previous Reverse an array in JavaScript Next Setting a Default route in Express.js Share your thoughts in the comments Add Your Comment Please Login to comment...