How to use Array Iteration In Javascript
Use the forEach method to iterate through each element of the input array and for each element in the input array, check if it exists in the unique array using the includes method. If the element is not already present in the unique array, push it into the unique array. Return the length of the unique array.
Example: To demonstrate the counting of unique elements in array using Array Iteration in JavaScript.
function countUniqueArray(arr) {
const unique = [];
arr.forEach(num => {
if (!unique.includes(num)) {
unique.push(num);
}
});
return unique.length;
}
const arr = [1, 2, 3, 1, 4, 2, 5];
console.log(countUniqueArray(arr));
Output
5
Time complexity: O(n2)
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