Skip to main content

JavaScript: Counting Same Occurrences in an Array

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:

  1. Create an empty object.
  2. Loop through the input array.
  3. While looping — for each of the array element — create an object property (key) of that.
  4. 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

The function example above will generate an object consists of elements of the array input as the object property and the array of index(es) where each was found as the value of the object property.

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! 👋

Monkey Raptor uses cookies for analytics, advertisements, and functionality. Privacy Policy