![]() |
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 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. Table of Content Using of JavaScript SetThe 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.
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. Using of indexOf() MethodThis 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.
Output true false Time Complexities: O(n^2), where N is the size of the array. Auxiliary space: O(1), no space required. Using Array.filter() and Array.includes()Using `Array.filter()` with a callback that checks if an element’s index is equal to its first occurrence’s index in the array (`Array.indexOf()`), the function filters out duplicate elements. The resulting array’s length equals the original if it contains only unique values. Example:
Output true false Using Array.sort() and Array.every()This approach involves sorting the array first and then checking if any consecutive elements are the same using Array.every(). Example: This example shows the use of the above-explained approach.
Output true false Using an object to track seen valuesUsing an object to track seen values involves iterating through the array and storing each value as a key in the object. If a value already exists as a key, it indicates a duplicate. This method is efficient for checking uniqueness in arrays. Example
Output true false |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |