- 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
Efficient algorithm for grouping elements and counting duplicates in JavaScript
We have got an array of objects. If one property of the object is the same as in another object, we consider it to be a duplicate entry.
We want to group objects by this property and store information about how many times the "duplicate" occurred.
X A B O Y X Z I Y X Z U X A B L Y X Z K
We want to group by the first value.
Another two properties are the same in each duplicate too, but comparing the first value will be enough.
We need to display to the user a result that looks like −
Y X Z (3) X A B (2)
Example
The code for this will be −
const arr = [ {x: 'x', acc: 'acc', val: 'val'}, {y: 'y', x: 'x', z: 'z'}, {y: 'y', x: 'x', z: 'z'}, {x: 'x', c: 'c', val: 'val'} ]; const countOccurrence = (arr = []) => { const res = {}; arr.forEach (item => { Object.keys( item ).forEach (prop => { ( res[prop] ) ? res[prop] += 1 : res[prop] = 1; }); }); return res; } const groupByOccurrence = (data = []) => { const obj = countOccurrence(data); const res = Object.keys ( obj ).reduce ( ( acc, val ) => { ( acc[obj[val]] ) ? acc[obj[val]].push ( val ) : acc[obj[val]] = [val]; return acc; }, {}); return res; } console.log(groupByOccurrence(arr));
Output
And the output in the console will be: { '1': [ 'acc', 'c' ], '2': [ 'val', 'y', 'z' ], '4': [ 'x' ] }
- Related Articles
- Counting duplicates and aggregating array of objects in JavaScript
- Function for counting frequency of space separated elements in JavaScript
- Grouping an Array and Counting items creating new array based on Groups in JavaScript
- Counting unique elements in an array in JavaScript
- Commons including duplicates in array elements in JavaScript
- JavaScript: Adjacent Elements Product Algorithm
- Counting below / par elements from an array - JavaScript
- Grouping array of array on the basis of elements in JavaScript
- Algorithm for matrix multiplication in JavaScript
- Counting the occurrences of JavaScript array elements and put in a new 2d array
- Counting smaller and greater in JavaScript
- Python – List Elements Grouping in Matrix
- Counting common elements in MySQL?
- Euclidean Algorithm for calculating GCD in JavaScript
- Grouping and sorting 2-D array in JavaScript

Advertisements