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

How Can I Count Duplicate Values in a JavaScript Array?

Mary-Kate Olsen
Release: 2024-12-02 04:29:10
Original
794 people have browsed it

How Can I Count Duplicate Values in a JavaScript Array?

Counting Duplicate Values in an Array in JavaScript

One of the common operations you might need to perform while working with arrays in JavaScript is counting the number of times each element appears. This can be useful for various scenarios, such as analyzing data or finding the most frequent values.

Consider an array that initially contains unique values:

var uniqueCount = ['a', 'b', 'c', 'd'];
Copy after login

After some operations, the array might have duplicate values:

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

To count the number of occurrences of each value in this array, you can use a simple approach.

Create an empty object called counts:

const counts = {};
Copy after login

Iterate through each element in the original array:

sampleArray.forEach(function (x) {
Copy after login

Inside the loop, check if the element exists as a key in the counts object. If it doesn't, initialize its count to 0. If it does, increment the count.

counts[x] = (counts[x] || 0) + 1;
Copy after login

After iterating through all elements, the counts object will contain the count for each unique value in the original array.

console.log(counts);
Copy after login

Expected output:

{
  a: 3,
  b: 2,
  c: 2,
  d: 2,
  e: 1,
  f: 1
}
Copy after login

This approach allows you to efficiently count duplicate values in an array, enabling you to perform further analysis or operations based on the frequency of elements.

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