In JavaScript the following will find the number of elements in the array. Assuming there to be a minimum of one element in the array
arr = ["jam", "beef", "cream", "jam"] arr.sort(); var count = 1; var results = ""; for (var i = 0; i < arr.length; i++) { if (arr[i] == arr[i+1]) { count +=1; } else { results += arr[i] + " --> " + count + " times\n" ; count=1; } }
Is it possible to do this without using sort() or without mutating the array in any way? I would imagine that the array would have to be re-created and then sort could be done on the newly created array, but I want to know what's the best way without sorting. And yes, I'm an artist, not a programmer, your honour.
To count the unique elements in an array, pass the array to the Set constructor and access the size property on the set. The Set object only stores unique values and automatically removes duplicates. The size property returns the number of values in the Set .
One simple solution is to use two nested loops. For every element, check if it repeats or not. If any element repeats, return false. If no element repeats, return false.
Method 1 : To check the status of visited elements create a array of size n and a variable say count_dis=0 to count the distinct element. Run a loop from index 0 to n and check if (visited[i]==1) then skip that element. Check if(arr[i]==arr[j]), then set visited[j]=1.
Calculate the length of an array using the length() function that will return an integer value as per the elements in an array. Call the sort function and pass the array and the size of an array as a parameter. Take a temporary variable that will store the count of distinct elements. Print the result.
A quick way to do this is to copy the unique elements into an Object.
var counts = {}; for (var i = 0; i < arr.length; i++) { counts[arr[i]] = 1 + (counts[arr[i]] || 0); }
When this loop is complete the counts
object will have the count of each distinct element of the array.
The fast way to do this is with a new Set()
object.
Sets are awesome and we should use them more often. They are fast, and supported by Chrome, Firefox, Microsoft Edge, and node.js.
— What is faster Set or Object? by Andrei Kashcha
The items in a Set
will always be unique, as it only keeps one copy of each value you put in. Here's a function that uses this property:
function countUnique(iterable) { return new Set(iterable).size; } console.log(countUnique('banana')); //=> 3 console.log(countUnique([5,6,5,6])); //=> 2 console.log(countUnique([window, document, window])); //=> 2
This can be used to count the items in any iterable (including an Array, String, TypedArray, and arguments object).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With