Home > Web Front-end > JS Tutorial > How Can I Count Array Element Occurrences in JavaScript and Return Unique Elements and Their Frequencies?

How Can I Count Array Element Occurrences in JavaScript and Return Unique Elements and Their Frequencies?

DDD
Release: 2024-12-19 08:58:13
Original
720 people have browsed it

How Can I Count Array Element Occurrences in JavaScript and Return Unique Elements and Their Frequencies?

Counting the Occurrences of Array Elements in JavaScript

This coding question asks for a way to count the occurrences of elements in an array and return two arrays: one containing the unique elements and the other containing the frequencies of each element. For instance, given the array [5, 5, 5, 2, 2, 2, 2, 2, 9, 4], the output arrays would be:

Unique Elements: 5, 2, 9, 4
Frequencies: 3, 5, 1, 1

The solution provided utilizes an object to count the occurrences. The code iterates through the original array and initializes a value of 1 in the counts object for each unique element it encounters. If an element already exists as a key in the object, its value is incremented by 1.

The result is a JavaScript object where each key is a unique element and each value is the frequency of that element's occurrence in the original array. The code then outputs the object, as well as the individual frequencies of specific elements for verification.

The above is the detailed content of How Can I Count Array Element Occurrences in JavaScript and Return Unique Elements and Their Frequencies?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template