- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Counting the occurrences of JavaScript array elements and put in a new 2d array
We are required to write a JavaScript function that takes in an array of literal values. The function should then count the frequency of each element of the input array and prepare a new array on that basis.
For example − If the input array is −
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];
Then the output should be −
const output = [ [5, 3], [2, 5], [9, 1], [4, 1] ];
Example
The code for this will be −
const arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4]; const frequencyArray = (arr = []) => { const res = []; arr.forEach(el => { if (!this[el]) { this[el] = [el, 0]; res.push(this[el]) }; this[el][1] ++ }, {}); return res; }; console.log(frequencyArray(arr));
Output
And the output in the console will be −
[ [ 5, 3 ], [ 2, 5 ], [ 9, 1 ], [ 4, 1 ] ]
- Related Articles
- Grouping an Array and Counting items creating new array based on Groups in JavaScript
- Counting unique elements in an array in JavaScript
- Unique number of occurrences of elements in an array in JavaScript
- Accumulating array elements to form new array in JavaScript
- Counting below / par elements from an array - JavaScript
- Counting frequencies of array elements in C++
- JavaScript - Constructs a new array whose elements are the difference between consecutive elements of the input array
- How to add new array elements at the beginning of an array in JavaScript?
- Counting occurrences of vowel, consonants - JavaScript
- Counting duplicates and aggregating array of objects in JavaScript
- Add two consecutive elements from the original array and display the result in a new array with JavaScript
- Turning a 2D array into a sparse array of arrays in JavaScript
- Counting elements of an array using a recursive function in JS?
- Find all occurrences of a word in array in JavaScript
- How do I declare a 2d array in C++ using new

Advertisements