JavaScript Program to Check if an Array Contains only Unique Values
Last Updated :
02 Jul, 2024
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.
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));
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.
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));
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:
JavaScript
function hasUniqueValues(arr) {
return arr.filter((value, index, self) => self.indexOf(value) === index).length === arr.length;
}
console.log(hasUniqueValues([1, 2, 3, 4, 5])); // true
console.log(hasUniqueValues([1, 2, 2, 3, 4])); // 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.
JavaScript
function checkDistinct(array) {
array.sort((a, b) => a - b);
return array.every((value, index) => index === 0 || value !== array[index - 1]);
}
// 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));
// Nikunj Sonigara
Using an object to track seen values
Using 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
JavaScript
function hasUniqueValues(arr) {
let seen = {};
for (let val of arr) {
if (seen[val]) {
return false;
}
seen[val] = true;
}
return true;
}
console.log(hasUniqueValues([1, 2, 3, 4]));
console.log(hasUniqueValues([1, 2, 2, 4]));
Similar Reads
JavaScript Program to Check if Kth Index Elements are Unique In this article, We have given a String list and a Kth index in which we have to check that each item in a list at that particular index should be unique. If they all are unique then we will print true in the console else we will print false in the console.Example:Input: test_list = [âgfgâ, âbestâ,
6 min read
JavaScript Program to Find the First Non-Repeated Element in an Array Finding the first non-repeated element in an array refers to identifying the initial occurrence of an element that does not occur again elsewhere within the array, indicating uniqueness among the elements.Examples: Input: {-1, 2, -1, 3, 0}Output: 2Explanation: The first number that does not repeat i
5 min read
JavaScript Program to Count Unequal Element Pairs from the Given Array Unequal element pairs in an array refer to pairs of distinct elements within the array that have different values. These pairs consist of two elements that are not equal to each other, highlighting their inequality when compared in the context of the array's values.Examples:Input: arr[] = {6, 5, 2,
4 min read
Checking for Duplicate Strings in JavaScript Array Checking for duplicate strings in a JavaScript array involves identifying if there are any repeated string values within the array. Given an array of strings a with size N, find all strings that occur more than once. If none is found, return [-1]. Example: Input: N = 4arr = ['apple', 'banana', 'oran
3 min read
How to Check an Array Contains only Unique Values in PHP? In PHP, verifying that an array contains unique values is a common task. This involves ensuring that each element in the array appears only once. There are multiple methods to achieve this check effectively:Table of ContentUsing array_unique () and count() functionUsing array_count_values() function
4 min read
How to check if an Array contains a value or not? There are many ways for checking whether the array contains any specific value or not, one of them is: Examples: Input: arr[] = {10, 30, 15, 17, 39, 13}, key = 17Output: True Input: arr[] = {3, 2, 1, 7, 10, 13}, key = 20Output: False Approach: Using in-built functions: In C language there is no in-b
3 min read
How to filter out the non-unique values in an array using JavaScript ? In JavaScript, arrays are the object using the index as the key of values. In this article, let us see how we can filter out all the non-unique values and in return get all the unique and non-repeating elements. These are the following ways by which we can filter out the non-unique values in an arra
4 min read
JavaScript Get all non-unique values from an array We have given a JavaScript array, and the task is to find all non-unique elements of the array. To get all non-unique values from the array here are a few examples. These are the following methods to get all non-unique values from an array:Table of ContentUsing Array Slice() MethodUsing for loopUsin
4 min read
JavaScript - How To Find Unique Characters of a String? Here are the various methods to find the unique characters of a string in JavaScript.1. Using Set (Most Common)The Set object is one of the easiest and most efficient ways to find unique characters. It automatically removes duplicates.JavaScriptconst s1 = "javascript"; const s2 = [...new Set(s1)]; c
3 min read
JavaScript Program to Print All Distinct Elements in an Integer Array Given an Array of Integers consisting of n elements with repeated elements, the task is to print all the distinct elements of the array using JavaScript. We can get the distinct elements by creating a set from the integer array. Examples: Input : arr = [ 1, 2, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9, 9 ] Outpu
3 min read