
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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' ] }
Advertisements