Hi!
For example, we have an array:
And we want to count the occurrence of every element in the array — how many times it appears.
Method
We can use Object construction method to achieve that.
The steps:
- Create an empty object.
- Loop through the input array.
- While looping — for each of the array element — create an object property (key) of that.
- The value of that object property (key) will be an array of index(es) where the input element is found.
Let's Go
It goes as such:
Usage
Let's take the example array above as the input. So then:
The output is an Object which consists of:
If you try that snippet with the input array in the JavaScript console, you'll be seeing something like this (expand it):
To get the length for each of the property, you can do like this:
Digest
Additional — Transformed Output
This additional snippet will output:
To access the array of index(es) of a particular element, do this:
And to access the length of a particular element:
Cheers! ð

