Javascript example GroupBy array of objects by key, property

You can also check other posts on Javascript Add, Delete from Array

javascript Object Array Groupby keys example

Sometimes after data is retrieved from the backend, We want to display the data using group by option. The array contains a list of the object where each object contains multiple keys and values.

There are multiple ways we can achieve group in the array of objects

First, let us declare an array of objects, each object holds the key and values of

var emps = [
  {
    name: "frank",
    id: 1,
    department: "sales",
  },
  {
    name: "john",
    id: 2,
    department: "hr",
  },
  {
    name: "eric",
    id: 3,
    department: "sales",
  },
  {
    name: "andrew",
    id: 4,
    department: "sales",
  },
];

lodash groupBy code examples

lodash is a popular library that provides a lot of useful inbuilt utility methods. This is very easy to implement in the projects ThegroupBy` method takes a collection of objects

_.groupBy(collection, [iteratee=_.identity])

input is an array of objects and iterate is the property of an object for grouping

following is an example grouping the employee object by department

var emps = [
  {
    name: "frank",
    id: 1,
    department: "sales",
  },
  {
    name: "john",
    id: 2,
    department: "hr",
  },
  {
    name: "eric",
    id: 3,
    department: "sales",
  },
  {
    name: "andrew",
    id: 4,
    department: "sales",
  },
];

_.groupBy(emps, "department");

And the output returns a group of departments

hr: [Object {department: "hr", id: 2, name: "john"}]
sales: [Object {department: "sales", id: 1, name: "frank"}, Object {department: "sales", id: 3, name: "eric"}

ES6 Array inbuilt reduce function groupby example

EcmaScript 2005 provides array inbuilt method reduce function. reduce function provides

function groupBy(arrayObjects, key) {
  return arrayObjects.reduce(function (result, currentObject) {
    const val = currentObject[key];
    result[val] = result[val] || [];
    result[val].push(currentObject);
    return result;
  }, {});
}

and output is

{ sales:
   [ { name: 'frank', id: 1, department: 'sales' },
     { name: 'eric', id: 3, department: 'sales' },
     { name: 'andrew', id: 4, department: 'sales' } ],
  hr: [ { name: 'john', id: 2, department: 'hr' } ] }

Conclusion

Learned multiple ways to group by an array of objects

  • using javascript reduce
  • Lodash groupBy function
  • Using Es6 features