Home >Web Front-end >JS Tutorial >How Can I Efficiently Count Duplicate Values in a JavaScript Array?

How Can I Efficiently Count Duplicate Values in a JavaScript Array?

Barbara Streisand
Barbara StreisandOriginal
2024-12-03 06:21:09579browse

How Can I Efficiently Count Duplicate Values in a JavaScript Array?

Counting Duplicate Values in Arrays with JavaScript

In programming, it's often necessary to identify and count duplicate values within an array. Let's consider an array like that:

var uniqueCount = Array();

After some operations, the array now holds:

uniqueCount = [a,b,c,d,d,e,a,b,c,f,g,h,h,h,e,a];

Our goal is to count how many occurrences of each unique value exist in this array. We aim for a result like:

a = 3
b = 1
c = 2
d = 2

One effective way to count duplicates in JavaScript is through the use of an object. Let's explore this solution:

const counts = {};
const sampleArray = ['a', 'a', 'b', 'c'];
sampleArray.forEach(function (x) { counts[x] = (counts[x] || 0) + 1; });
console.log(counts);

This code utilizes an object named counts to store the frequency of each value in the sampleArray. The forEach method loops through the array, and for each value encountered, the counts object is updated. If the value is already present in the object, its count is incremented; otherwise, it's initialized to one. Finally, the counts object is logged to the console, providing the desired output:

{ a: 2, b: 1, c: 1 }

The above is the detailed content of How Can I Efficiently Count Duplicate Values 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