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
Release: 2024-12-03 06:21:09
Original
574 people have browsed it

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();
Copy after login

After some operations, the array now holds:

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

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

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

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

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!

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