Efficient algorithm for grouping elements and counting duplicates in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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' ] }
raja
Published on 24-Nov-2020 10:40:12
Advertisements