Home >Web Front-end >JS Tutorial >How Can I Efficiently Count the Frequency of Elements in a JavaScript Array?

How Can I Efficiently Count the Frequency of Elements in a JavaScript Array?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-30 02:18:13557browse

How Can I Efficiently Count the Frequency of Elements in a JavaScript Array?

Counting the Occurrences / Frequency of Array Elements

Counting the frequency of array elements is a common programming task, and JavaScript provides various methods to achieve this. One effective approach involves utilizing an object. Let's dive into a detailed solution.

Object-Based Method

Create an empty object to hold the counts.

const counts = {};

Iterate through each element in the original array.

for (const num of arr) {

For each element, check if it exists as a property in the counts object.

if (counts[num]) {

If the property exists, increment its value by 1.

  counts[num] += 1;

If the property doesn't exist, set its value to 1.

} else {
  counts[num] = 1;
}

Example

Consider the following input array:

[5, 5, 5, 2, 2, 2, 2, 2, 9, 4]

Using the object-based method, we get the following result:

{ 5: 3, 2: 5, 9: 1, 4: 1 }

Accessing Individual Counts

To access the count for a specific element, use the property name, which is the element itself.

console.log(counts[5]); // Output: 3
console.log(counts[2]); // Output: 5

The above is the detailed content of How Can I Efficiently Count the Frequency of Elements in a JavaScript Array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn