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
Release: 2024-12-30 02:18:13
Original
553 people have browsed it

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 = {};
Copy after login

Iterate through each element in the original array.

for (const num of arr) {
Copy after login

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

if (counts[num]) {
Copy after login

If the property exists, increment its value by 1.

  counts[num] += 1;
Copy after login

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

} else {
  counts[num] = 1;
}
Copy after login

Example

Consider the following input array:

[5, 5, 5, 2, 2, 2, 2, 2, 9, 4]
Copy after login

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

{ 5: 3, 2: 5, 9: 1, 4: 1 }
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template