Horje
GFact | Most efficient method to groupby on an array of objects in Javascript

The most efficient method to group by a key on an array of objects in JavaScript is to use the reduce function.

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value. It applies a function to each element of an array, accumulating a single result, and returns the final output.

Syntax:

array.reduce( function(total, currentValue, currentIndex, arr), initialValue );

Example:

Javascript

const people = [
  { name: 'Lee', age: 21 },
  { name: 'Ajay', age: 20 },
  { name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
  return objectArray.reduce((acc, obj) => {
     const key = obj[property];
     if (!acc[key]) {
        acc[key] = [];
     }
     // Add object to list for given key's value
     acc[key].push(obj);
     return acc;
  }, {});
}
const groupedPeople = groupBy(people, 'age');
console.log(groupedPeople);

Output

{
  '20': [ { name: 'Ajay', age: 20 }, { name: 'Jane', age: 20 } ],
  '21': [ { name: 'Lee', age: 21 } ]
}



Reffered: https://www.geeksforgeeks.org


GFacts

Related
GFact | Why Printing Boolean in C++ Display as 0 and 1 GFact | Why Printing Boolean in C++ Display as 0 and 1
GFact | Why is Floating Point Arithmetic a problem in computing? GFact | Why is Floating Point Arithmetic a problem in computing?
Gfact | Which is Faster - Pre-increment (++i) vs Post-increment (i++)? Gfact | Which is Faster - Pre-increment (++i) vs Post-increment (i++)?
Can C++ reference member be declared without being initialized with declaration? Can C++ reference member be declared without being initialized with declaration?
Nesbitt's Inequality Nesbitt's Inequality

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14