Open In App

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

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
2 Likes
Like
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.

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:


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:


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.


Output
[ 1, 2, 3, 4, 5 ]

Next Article

Similar Reads