How to use a Set In Javascript
Initialize a new Set. Use the Set’s constructor to create a Set from the input array arr. This will automatically remove duplicates as Sets only store unique elements. Return the size of set.
Example: To demonstrate the counting of unique elements in array using a set method in JavaScript.
function countUniqueSet(arr) {
// Create a Set to s
// tore unique elements
const uniqueSet = new Set(arr);
// Return the size of the Set,
// which represents the count of unique elements
return uniqueSet.size;
}
const arr = [1, 2, 3, 1, 4, 2, 5];
console.log(countUniqueSet(arr));
Output
5
Time complexity: O(n)
Space complexity: O(n)
Count Unique Elements in Array Without Sorting using JavaScript
One can count unique elements(distinct elements) present in an array without sorting JavaScript. There are several methods of counting unique elements without sorting in JavaScript. Below is an example to understand the problem clearly.
Example:
Input: [ 1,2, 3, 1, 3, 4, 5, 5, 2]
Output: 5
Explanation: Unique Elements in array : 1, 2, 3, 4, 5. Total 5 unique elements present in array
There are several approaches to count unique elements in array without sorting in JavaScript which are as follows:
Table of Content
- Using Array Iteration
- Using a Set
- Using an object/Map
Contact Us