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.
Table of Content
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:
// 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 ]
Method 2: Using a set and checking its size
Remember that a set does not allow duplicate elements.
Example:
// 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)
Output
[ 41, 75, 57, 62, 92 ]
Method 3: Using forEach and includes method
Using forEach and includes to remove duplicates involves iterating over the array and adding each item to a new array only if it isn’t already included. This ensures all elements in the result are unique.
Example: The removeDuplicates function iterates through an array (`arr`), checking each element. If an element isn’t already in nonRepeatingArray, it adds it. This ensures `nonRepeatingArray` contains only unique elements.
function removeDuplicates(arr) {
const nonRepeatingArray = [];
arr.forEach(item => {
if (!nonRepeatingArray.includes(item)) {
nonRepeatingArray.push(item);
}
});
return nonRepeatingArray;
}
const arrayWithDuplicates = [1, 2, 3, 4, 2, 3, 5, 1];
const result = removeDuplicates(arrayWithDuplicates);
console.log(result);
Output
[ 1, 2, 3, 4, 5 ]