Open In App

JavaScript Program to Check if an Array Contains only Unique Values

Last Updated : 27 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are given an array, Our task is to find whether the elements in an array are unique or not.

Examples:

Input 1: 7,8,1,5,9                                                                                                                                                                                  
Output: true

Input2: 7,8,1,5,5
Output: false

In Input 1, elements 7,8,1,5,9 are distinct from each other and they were unique, there was no repetition of elements hence the array contains unique values. So the output is true, else the output is false.

Approach 1: Using of JavaScript Set

The set data structure is used to store the unique elements, it won’t store the repeated or duplicate elements. If the size of the newly created set is equal to the size of the array, then the array contains unique elements. If not, it means the array contains duplicate or repeated elements.

Example: This example shows the use of the above-explained approach.

Javascript




// JavaScript Approach using Set
  
function checkDistinct(array) {
    const checkSet = new Set(array);
      
    // Strict equality 
    // Return boolean value
    return checkSet.size === array.length;  
}
  
// Input 1
const input1 = [7, 8, 1, 5, 9];
console.log(checkDistinct(input1));
  
// Input 2
const input2 = [7, 8, 1, 5, 5];
console.log(checkDistinct(input2));


Output

true
false

Time Complexity: O(N), N is the no of elements in the given array.

Auxiliary Space: O(N) , because of creating a Set Data Structure.

Approach 2: Using of indexOf() Method

This method is used to find the index of the first occurrence of the element. If the elements in the array are distinct, then the value returned by the indexOf() method is equal to the index of the element in the array. If repeated elements are present in the array, then the indexOf() method will return the first occurrence of the repeated element, hence the returned value and index of the element will differ.

Example: This example shows the use of the above-explained approach.

Javascript




//JavaScript Program using indexOf() method
  
function checkDistinct(array) {
    for (let i = 0; i < array.length; i++) {
        if (array.indexOf(array[i]) !== i) {
            return false;
        }
    }
    return true;
}
  
// Input1
const input1 = [7, 8, 1, 5, 9];
console.log(checkDistinct(input1));
  
//Input2
const input2 = [7, 8, 1, 5, 5];
console.log(checkDistinct(input2));


Output

true
false

Time Complexities: O(n^2), where N is the size of the array.

Auxiliary space: O(1), no space required.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads