Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA Tutorial
  • Data Structures
  • Algorithms
  • Array
  • Strings
  • Linked List
  • Stack
  • Queue
  • Tree
  • Graph
  • Searching
  • Sorting
  • Recursion
  • Dynamic Programming
  • Binary Tree
  • Binary Search Tree
  • Heap
  • Hashing
  • Divide & Conquer
  • Mathematical
  • Geometric
  • Bitwise
  • Greedy
  • Backtracking
  • Branch and Bound
  • Matrix
  • Pattern Searching
  • Randomized
Open In App
Next Article:
JavaScript- Count Frequencies in an Array
Next article icon

JavaScript- Count Frequencies in an Array

Last Updated : 19 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

These are the following ways to count the frequency:

1. Using Object (Efficient for Small to Moderate Arrays)

We use JavaScript Objects to store frequencies, we iterate over the array using the forEach() method. For each element, we check if the element already exists as a key in the res object. If it does, we increment its count; if not, we initialize it to 1.

JavaScript
const a = [4, 2, 3, 4, 3, 2, 4, 1, 3, 2]; let res = {};   a.forEach(e => {     res[e] = (res[e] || 0) + 1;   }); console.log(res);   

2. Using Map (Easiest and Efficient for All Types of Arrays)

Here, we use a Map to store the frequency of each element. We iterate over the array using forEach() and use the get() method to check if the element is already in the Map.

JavaScript
const a1 = [4, 2, 3, 4, 3, 2, 4, 1, 3, 2]; let res = new Map();  a1.forEach(e => {     res.set(e, (res.get(e) || 0) + 1);   }); console.log(Object.fromEntries(res));   

Output
{ '1': 1, '2': 3, '3': 3, '4': 3 } 

3. Using reduce() with Map (Similar to 2nd)

This approach uses the reduce() method, which is typically used to accumulate results. We can also use reduce with Objects.

JavaScript
const a = [4, 2, 3, 4, 3, 2, 4, 1, 3, 2]; let res = a.reduce((acc, e) => {     acc.set(e, (acc.get(e) || 0) + 1);      return acc;   }, new Map()); console.log(res);  

Output
{ '1': 1, '2': 3, '3': 3, '4': 3 } 

4. Using for...of Loop Object (Similar to 2nd, only loop is different)

This approach uses the for...of loop to iterate through each element of the array and store frequencies in Map. We can also use this with Object.

JavaScript
const a = [4, 2, 3, 4, 3, 2, 4, 1, 3, 2]; let res = new Map();  for (const e of a) {     res.set(e, (res.get(e) || 0) + 1);  }  console.log(res);  

Output
{ '1': 1, '2': 3, '3': 3, '4': 3 } 

Next Article
JavaScript- Count Frequencies in an Array

M

meetahaloyx4
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • DSA
  • javascript-array

Similar Reads

    Count Frequency of an Array Item in JavaScript
    Here are the different approaches to count the frequency of an Array Item in JavaScriptUsing a Loop and CounterThis is the most basic and efficient approach when you want to find the frequency of a single item. You simply loop through the array and count how many times the item appears.JavaScriptcon
    2 min read
    JavaScript - Counting Frequencies of Array Elements
    Here are the various approaches to count the frequencies of array elements in JavaScript.Using an Object (Simple and Efficient)This is the most common approach for counting frequency in an array. Each array element becomes a key in the object, and its value is incremented as the element appears.Java
    2 min read
    Count indices with Specific Frequency in Array Range
    Given an array of N elements and num queries, In each query, you are given three numbers L, R, and K and you have to tell, how many indexes are there in between L and R(L <= i <= R) such that the frequency of a[i] from index i to n-1 is K. Follow 0-based indexing Examples: Input: N = 5, num =
    11 min read
    Frequency of an element in an array
    Given an array, a[], and an element x, find a number of occurrences of x in a[].Examples: Input : a[] = {0, 5, 5, 5, 4} x = 5Output : 3Input : a[] = {1, 2, 3} x = 4Output : 0Unsorted ArrayThe idea is simple, we initialize count as 0. We traverse the array in a linear fashion. For every element that
    9 min read
    Counting frequencies of array elements
    Given an array which may contain duplicates, print all elements and their frequencies. Examples: Input : arr[] = {10, 20, 20, 10, 10, 20, 5, 20}Output : 10 3 20 4 5 1Input : arr[] = {10, 20, 20}Output : 10 1 20 2 A simple solution is to run two loops. For every item count number of times, it occurs.
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences